CODESCRIPT

Strategy

97 entries. What each one takes, what it returns, and a working example.

accountCurrency()

Returns the account currency — currently the constant "USD".

NOTE

The value is constant ("USD"); multi-currency/FX conversion is not modeled yet.

CODESCRIPT
label(close, accountCurrency())

Attaches the currency label (USD) to price.

alert(message, freq?)

Does not return a value; it produces an alert event when the condition turns from false to true on the last bar.

condition
bool
Fires an alert on a false-to-true transition.
title
string
Optional. Alert title.
message
string
Optional. Alert message.
NOTE

v0.1: run output only; the alert center will be connected in a later phase.

alertcondition(condition, title?, message?)

Returns nothing; registers an alert on the rising edge (false→true) of the condition.

koşul
bool
The condition the alert is defined on; fires on the false→true edge (last bar).
title
string
Optional. Alert title (default "Alarm").
message
string
Optional. Alert message.
NOTE

Distinct from `alert()`: `alertcondition` is condition-based and edge-triggered (the first bar the condition turns true). Takes a compile-time constant title/message.

CODESCRIPT
alertcondition(crossover(close, sma(close, 50)), "Kesişim", "Fiyat SMA50'yi yukarı kesti")

Alerts on the bar where price crosses above SMA50.

allowEntryIn(yön)

Returns nothing. Prevents opening a new position in the disallowed direction.

yön
string
Allowed entry direction: strategy.direction.long, strategy.direction.short, or strategy.direction.all.
NOTE

When a signal arrives in the disallowed direction, no new position opens; an open opposite position is CLOSED (not reversed). strategy.direction.all (default) applies no restriction.

CODESCRIPT
allowEntryIn(strategy.direction.long)
enterLong(rsi(close,14) < 30)
enterShort(rsi(close,14) > 70)

When the short signal arrives, the open long closes; no new short opens.

avgLosingTrade()

Average percent loss of closed losing trades (running, positive-abs).

NOTE

Percent-primary; *Currency suffix gives absolute currency (pnlPct/100 x notional). Losing metrics are positive-abs, consistent with grossLoss.

avgLosingTradeCurrency()

Average absolute-currency loss of closed losing trades (running, positive).

NOTE

Percent-primary; *Currency suffix gives absolute currency (pnlPct/100 x notional). Losing metrics are positive-abs, consistent with grossLoss.

avgTrade()

Returns the average profit/loss per trade ((gross profit − gross loss) / closed trades) as a running series.

NOTE

Returns 0 when there are no closed trades yet (no division by zero).

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(avgTrade(), "Ort. İşlem")

Plots the average per-trade result.

avgTradeCurrency()

Average absolute-currency P&L of all closed trades (running).

NOTE

The absolute-currency version of avgTrade (pnlPct/100 x notional). The percent name (avgTrade) is unchanged and backward-compatible.

avgWinningTrade()

Average percent profit of closed winning trades (running).

NOTE

Percent-primary; *Currency suffix gives absolute currency (pnlPct/100 x notional). Losing metrics are positive-abs, consistent with grossLoss.

avgWinningTradeCurrency()

Average absolute-currency profit of closed winning trades (running).

NOTE

Percent-primary; *Currency suffix gives absolute currency (pnlPct/100 x notional). Losing metrics are positive-abs, consistent with grossLoss.

cancel(id[, when])

Returns nothing; it cancels the pending order with the given id.

id
string
Constant string id of the order to cancel.
when
bool
Optional. Cancel condition (if omitted, every bar).
NOTE

The same id is cleared from both a pending entry (limit/stop) order and a pending exit order. If no such order exists, it does nothing.

CODESCRIPT
enterLong(barIndex==0, id='A', limit=close*0.98)
cancel('A', when=barIndex==3)
exit(barIndex==40)

The 'A' limit order placed on bar 0 is cancelled on bar 3 if it has not filled.

CODESCRIPT
enterLong(barIndex==0, id='A', limit=close*0.97)
cancel('A', when=close < lowest(low,20))
exit(barIndex==40)

If price breaks below the 20-bar low, the 'A' limit order is canceled and no trade opens.

cancelAll([when])

Returns nothing; it cancels all pending orders.

when
bool
Optional. Cancel condition (if omitted, every bar).
NOTE

All pending entry and pending exit orders are cleared together.

CODESCRIPT
enterLong(barIndex==0, id='A', limit=close*0.98)
enterLong(barIndex==0, id='B', stop=close*1.02)
cancelAll(when=barIndex==2)
exit(barIndex==40)

On bar 2 both the A and B pending orders are cancelled; if unfilled, no trade opens.

CODESCRIPT
enterLong(barIndex==0, id='A', limit=close*0.98)
enterShort(barIndex==0, id='B', stop=close*1.02)
cancelAll(when=rsi(close,14) > 60)
exit(barIndex==40)

When RSI rises above 60, both the A and B pending orders are cleared.

cash()

Returns the same equity series as `equity()`.

NOTE

Alias of `equity()`.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(cash(), "Nakit")

Plots the equity curve.

closeAll(kosul?)

Returns nothing. On a bar where the condition is true, closes the ENTIRE open position (all legs) at market — at the open of the NEXT bar after the signal.

kosul
bool
Close condition; the entire open position closes on a bar where it is true. Closes every bar if omitted.
NOTE

Uses the same exit path and timing as exit() (a market exit fills at the next bar's open) but without the fromEntry/qtyPct filter — it always closes all. Closes every remaining leg in a pyramided or partially-closed position. Calling it with no open position does nothing.

CODESCRIPT
enterLong(crossover(close, sma(close,20)))
closeAll(crossunder(close, sma(close,20)))
plot(close)

Buys when price crosses above the 20-period average, closes the whole position when it crosses below.

closePart(koşul, oran?)

Returns nothing; calls `exit(condition)` on the true bar (full exit).

koşul
bool
Closes the open position on bars where this is true.
oran
number
Optional. Reserved for the fraction (%) to close; NOT yet applied — the call performs a full exit.
NOTE

NOTE: the `oran` (ratio) parameter exists in the signature but currently has no effect — a FULL close is performed, not partial. For partial exits use `exit(condition, qtyPct=...)`.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
closePart(crossunder(close, sma(close, 30)))

Fully closes the position on the down-cross.

closedTradeCommission(n)

The closed trade's round-trip (entry+exit) commission cost — in currency.

n
number
Trade index (0 first, -1 last).
NOTE

The sum of entry and exit commission (commission rate only; slippage NOT included). Leverage/margin and position size are accounted for.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(closedTradeCommission(-1), "Komisyon")

Returns the last closed trade's round-trip commission cost.

closedTradeEntryBar(n)

Returns the entry bar index of the n-th closed trade (resolved from entry time).

n
number
0-based index of the closed trade; negative counts from the end (default -1).
CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(closedTradeEntryBar(-1), "Giriş Barı")

Plots the last trade's entry bar index.

closedTradeEntryComment(n)

Entry comment — NOT tracked; returns empty string.

n
number
Trade index (no effect — a constant is returned).
NOTE

This field is not tracked yet; always returns an empty string (present for syntax compatibility).

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
label(close, closedTradeEntryComment(-1))

Returns empty string (no comment tracking).

closedTradeEntryId(n)

Entry order id — NOT tracked; returns empty string.

n
number
Trade index (no effect — a constant is returned).
NOTE

This field is not tracked yet; always returns an empty string (present for syntax compatibility).

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
label(close, closedTradeEntryId(-1))

Returns empty string (no id tracking).

closedTradeEntryPrice(n)

Entry price of the n-th closed trade — alias of `tradeEntryPrice(n)`.

n
number
0-based index of the closed trade; negative counts from the end (default 0).
CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(closedTradeEntryPrice(0), "Giriş")

Plots the closed trade's entry price.

closedTradeEntryTime(n)

Entry time of the n-th closed trade — alias of `tradeEntryTime(n)`.

n
number
0-based index of the closed trade; negative counts from the end (default 0).
CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(closedTradeEntryTime(0), "Giriş Zamanı")

Plots the closed trade's entry time.

closedTradeExitBar(n)

Returns the exit bar index of the n-th closed trade (resolved from exit time).

n
number
0-based index of the closed trade; negative counts from the end (default -1).
CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(closedTradeExitBar(-1), "Çıkış Barı")

Plots the last trade's exit bar index.

closedTradeExitComment(n)

Returns the exit reason/comment (text) of the n-th closed trade; empty string if none.

n
number
0-based index of the closed trade; negative counts from the end (default -1).
CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
label(close, closedTradeExitComment(-1))

Labels the last trade's exit reason.

closedTradeExitId(n)

Exit order id — NOT tracked; returns empty string.

n
number
Trade index (no effect — a constant is returned).
NOTE

This field is not tracked yet; always returns an empty string (present for syntax compatibility).

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
label(close, closedTradeExitId(-1))

Returns empty string.

closedTradeExitPrice(n)

Exit price of the n-th closed trade — alias of `tradeExitPrice(n)`.

n
number
0-based index of the closed trade; negative counts from the end (default 0).
CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(closedTradeExitPrice(0), "Çıkış")

Plots the closed trade's exit price.

closedTradeExitReason(n?)

The automatic exit reason code (signal/stop/target/trail/partial1/partial2/eod/liq/manual/risk/exit).

n
number
Optional trade index (0 = first, negative = from the end).
NOTE

This value used to be returned by closedTradeExitComment() by mistake; they are now separate: comment = user note, reason = automatic reason code.

closedTradeExitTime(n)

Exit time of the n-th closed trade — alias of `tradeExitTime(n)`.

n
number
0-based index of the closed trade; negative counts from the end (default 0).
CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(closedTradeExitTime(0), "Çıkış Zamanı")

Plots the closed trade's exit time.

closedTradeMaxDrawdown(n)

The worst drawdown (MAE) the closed trade suffered during its life — in currency.

n
number
Trade index (0 first, -1 last).
NOTE

Pure price movement: commission and carry EXCLUDED — 'how far price went against you', not the account-balance swing. Uses the lowest low for longs, the highest high for shorts; entry and exit bars are included.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(closedTradeMaxDrawdown(-1), "MAE")

Returns the last closed trade's worst drawdown in currency.

closedTradeMaxDrawdownPercent(n)

The closed trade's worst drawdown (MAE) — percent.

n
number
Trade index (0 first, -1 last).
NOTE

Pure price movement: commission/carry EXCLUDED. Lowest low for longs, highest high for shorts; entry and exit bars included. The percent is on the same scale as P&L percent (leverage included).

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(closedTradeMaxDrawdownPercent(-1), "MAE %")

Returns the last closed trade's worst drawdown percent.

closedTradeMaxRunup(n)

The best run-up (MFE) the closed trade reached during its life — in currency.

n
number
Trade index (0 first, -1 last).
NOTE

Pure price movement: commission and carry EXCLUDED — 'how far price went in your favor'. Uses the highest high for longs, the lowest low for shorts; entry and exit bars are included.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(closedTradeMaxRunup(-1), "MFE")

Returns the last closed trade's best run-up in currency.

closedTradeMaxRunupPercent(n)

The closed trade's best run-up (MFE) — percent.

n
number
Trade index (0 first, -1 last).
NOTE

Pure price movement: commission/carry EXCLUDED. Highest high for longs, lowest low for shorts; entry and exit bars included. The percent is on the same scale as P&L percent (leverage included).

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(closedTradeMaxRunupPercent(-1), "MFE %")

Returns the last closed trade's best run-up percent.

closedTradeProfit(n)

Returns the n-th closed trade's profit/loss in CURRENCY (pnl% × initial capital / 100).

n
number
0-based index of the closed trade; negative counts from the end (default -1).
NOTE

In currency units. For percent use `closedTradeProfitPercent(n)`.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(closedTradeProfit(-1), "Son İşlem K/Z")

Plots the last closed trade's currency P/L.

closedTradeProfitPercent(n)

Returns the n-th closed trade's profit/loss as a PERCENT (pnl%).

n
number
0-based index of the closed trade; negative counts from the end (default -1).
CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(closedTradeProfitPercent(-1), "Son İşlem %")

Plots the last closed trade's percent P/L.

closedTradeSize(n)

Direction/size of the n-th closed trade — alias of `tradeSize(n)`.

n
number
0-based index of the closed trade; negative counts from the end (default 0).
CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(closedTradeSize(0), "Yön")

Plots the closed trade's direction.

closedTrades()

Returns the total number of closed trades so far, as a running series.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(closedTrades(), "Kapanan İşlem")

Plots cumulative closed-trade count.

closedTradesCount()

Returns the total closed-trade count — identical to `tradeCount()`.

NOTE

Alias of `tradeCount()`.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(closedTradesCount(), "Kapanan")

Plots the closed-trade count.

closedTradesFirstIndex()

First index of the closed trade list. Trade history is never trimmed here (no cap), so it always returns 0. Provided so that `for i = closedTradesFirstIndex() to...` loops ported from referans dil keep working.

convertToAccount(değer)

Returns the value UNCHANGED (identity). Since the account and symbol currency are assumed equal, no FX conversion is applied.

değer
number
The value to convert.
NOTE

Exists for syntax compatibility; real FX conversion is not modeled (accountCurrency is the constant "USD").

CODESCRIPT
plot(convertToAccount(close), "Değer")

Plots the value unchanged.

convertToSymbol(değer)

Returns the value UNCHANGED (identity). No FX conversion is applied.

değer
number
The value to convert.
NOTE

Same as `convertToAccount` — passthrough placeholder; no FX model.

CODESCRIPT
plot(convertToSymbol(close), "Değer")

Plots the value unchanged.

defaultEntryQty(adet)

Returns nothing. When called, sizing switches from the default %equity to a fixed quantity; P&L = quantity × price change.

adet
number
Fixed quantity (contracts/shares) taken per trade.
NOTE

If never called, the default %equity sizing is kept (existing strategies are unaffected). In quantity mode leverage does not enter P&L; it only sets required margin and the liquidation threshold. If margin is insufficient the trade is skipped (quantity is not trimmed).

CODESCRIPT
defaultEntryQty(2)
enterLong(crossover(close, sma(close, 20)))
exit(crossunder(close, sma(close, 20)))
plot(close)

Takes a fixed 2 units per trade; P&L is computed as 2 × price change.

drawdownPct()

Returns the drawdown from the running equity peak (max drawdown) as a percentage.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(drawdownPct(), "Geri-çekilme %")

Plots the running drawdown percentage.

enterLong(condition, stopLoss?, takeProfit?, trailingStop?, id?, limit?, stop?, ocaGroup?, qty?, comment?, stopLossTicks?, takeProfitTicks?, trailTicks?, trailOffsetTicks?, trailFar?, trailNear?, trailThresh1?, trailThresh2?, stopLossAtr?, partial1Pct?, partial1Size?, partial2Pct?, partial2Size?)

Returns nothing; it reports an entry order to the strategy test.

condition
bool
Opens a long position on the bar where this is true.
stopLoss
number
Optional. Percent stop-loss relative to entry.
takeProfit
number
Optional. Percent take-profit relative to entry.
trailingStop
number
Optional. Percent-based trailing stop.
id
string
Optional. Constant-text entry id (for fromEntry/pyramiding).
limit
number
Optional. Pending limit price (fills when price FALLS to it).
stop
number
Optional. Pending stop price (fills when price RISES to it). Cannot be given together with limit.
ocaGroup
string
Optional. Constant-text group tag (for id'd pending entries). When one order in the group fills, its siblings are auto-cancelled — for competing setups (one filling drops the other).
NOTE

Risk values are percentages (stopLoss=2 means 2%). A market order (no limit/stop) fills at the open of the NEXT bar after the signal — an order can't fill before its own bar closes (realistic timing). If limit or stop is given, a pending order is set up instead (the two are not used together); pending orders fill within the bar when price reaches the level. id + limit/stop gives a pending order list: the same id updates it, different ids wait together. When one of the pending entries sharing an ocaGroup fills, its siblings are auto-cancelled (competing setup: arm a breakout and a pullback order together — the first fill drops the other). With pyramiding(n), up to n entry legs can be added in the same direction.

TIP

The rule is passed straight in as a condition; there is no separate order function. Pending orders and scaled entries are all handled by the same call.

CODESCRIPT
enterLong(crossover(close, sma(close,20)))
exit(crossunder(close, sma(close,20)))

BUY when price crosses above SMA20, close when it crosses below.

CODESCRIPT
enterLong(barIndex==0, limit=sma(close,20)*0.98)
exit(barIndex==40)

A pending limit 2% below SMA20; fills when price drops to that level.

enterShort(condition, stopLoss?, takeProfit?, trailingStop?, id?, limit?, stop?, ocaGroup?, qty?, comment?, stopLossTicks?, takeProfitTicks?, trailTicks?, trailOffsetTicks?, trailFar?, trailNear?, trailThresh1?, trailThresh2?, stopLossAtr?, partial1Pct?, partial1Size?, partial2Pct?, partial2Size?)

Returns nothing; it reports a short entry order to the strategy test.

condition
bool
Opens a short position on the bar where this is true.
stopLoss
number
Optional. Percent stop-loss relative to entry.
takeProfit
number
Optional. Percent take-profit relative to entry.
trailingStop
number
Optional. Percent-based trailing stop.
id
string
Optional. Constant-text entry id.
limit
number
Optional. Pending limit price.
stop
number
Optional. Pending stop price. Cannot be given together with limit.
NOTE

The short counterpart of enterLong; the same id/limit/stop/pyramiding/ocaGroup rules and fill timing apply (a market order fills at the next bar's open after the signal), and risk values are percentages.

CODESCRIPT
enterShort(crossunder(close, sma(close,20)))
exit(crossover(close, sma(close,20)))

SELL when price crosses below SMA20, close when it crosses above.

CODESCRIPT
enterShort(barIndex==0, id='S', stop=sma(close,20)*1.02)
exit(barIndex==40)

A pending stop 2% above SMA20; the short fills when price rises to that level.

entryComment()

The comment string of the active position's entry order; empty string when flat.

NOTE

Reads the plain-text note set via enterLong/Short(comment=...). Separate from id (no tracking/cancel). With pyramiding, the last-added leg's comment is active.

entryMarket(koşul, yön?)

Returns nothing; routes a market order on the true bar. A thin wrapper over enterLong/enterShort.

koşul
bool
Enters a position with a market order on bars where this is true.
yön
string
Optional. "short"/false → short; otherwise long (default long).
NOTE

`order` is an alias for this (identical behavior). The direction argument picks long/short in one call; for stop/take-profit risk arguments use enterLong/enterShort.

CODESCRIPT
yon = close > open ? "long" : "short"
entryMarket(crossover(close, sma(close, 20)), yon)

On the crossover bar, a long or short market order depending on the candle direction.

equity()

Returns the backtest equity series (post-risk, pre-order, valued at bar close).

NOTE

If initial capital is unset, 10000 is assumed. `cash()` is an alias of this.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(equity(), "Sermaye")

Plots the equity curve on a sub-panel.

exit(condition, fromEntry?, qtyPct?, id?, limit?, stop?, comment?, commentProfit?, commentLoss?)

Returns nothing; it triggers a market exit (at the next bar's open) or sets up an id-tagged resting exit order.

condition
bool
Triggers an exit on the bar where this is true; for pending orders this condition arms the order.
fromEntry
string
Optional. Constant text; targets only the entry lot with this id (otherwise all open entry lots).
qtyPct
number
Optional. What percent of the remaining targeted entry lots to close (otherwise 100%).
id
string
Optional. Id of the pending exit order (required together with limit/stop).
limit
number
Optional. Pending take-profit price.
stop
number
Optional. Pending stop-loss price.
NOTE

If limit/stop is not given, a market exit occurs: it fills at the open of the NEXT bar after the signal (realistic timing, like entries). Only limit or only stop gives an identified pending exit (fills within the bar when price reaches the level). limit and stop together give a bracket (take-profit + stop-loss pair): when one fills, the other is automatically canceled (OCO). qtyPct closes partially; the bracket is one-shot (once filled it is removed, and the remaining entry part is left unprotected).

TIP

A single call handles both a market exit and a resting take-profit / stop-loss; when limit and stop are given together, filling one cancels the other.

CODESCRIPT
enterLong(crossover(close, sma(close,10)))
exit(crossunder(close, sma(close,10)))

Rule-based immediate exit: close when SMA10 is crossed downward.

CODESCRIPT
enterLong(barIndex==0, id='L')
exit(barIndex==5, fromEntry='L', qtyPct=50)
exit(barIndex==40)

On bar 5 only 50% of the L entry part is closed; the remainder on bar 40.

grossLoss()

Returns the total loss of losing closed trades (gross loss, positive magnitude) as a running series.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(grossLoss(), "Brüt Zarar")

Plots cumulative gross loss.

grossLossCurrency()

Total absolute-currency loss of closed losing trades (running, positive).

NOTE

The absolute-currency version of grossLoss (pnlPct/100 x notional). The percent name (grossLoss) is unchanged and backward-compatible.

grossProfit()

Returns the total profit of winning closed trades (gross profit) as a running series.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(grossProfit(), "Brüt Kâr")

Plots cumulative gross profit.

grossProfitCurrency()

Total absolute-currency profit of closed winning trades so far (running).

NOTE

The absolute-currency version of grossProfit (pnlPct/100 x notional). The percent name (grossProfit) is unchanged and backward-compatible.

largestLosingTrade()

Largest single-trade percent loss (running, positive-abs).

NOTE

Percent-primary; *Currency suffix gives absolute currency (pnlPct/100 x notional). Losing metrics are positive-abs, consistent with grossLoss.

largestLosingTradeCurrency()

Largest single-trade absolute-currency loss (running, positive).

NOTE

Percent-primary; *Currency suffix gives absolute currency (pnlPct/100 x notional). Losing metrics are positive-abs, consistent with grossLoss.

largestWinningTrade()

Largest single-trade percent profit (running).

NOTE

Percent-primary; *Currency suffix gives absolute currency (pnlPct/100 x notional). Losing metrics are positive-abs, consistent with grossLoss.

largestWinningTradeCurrency()

Largest single-trade absolute-currency profit (running).

NOTE

Percent-primary; *Currency suffix gives absolute currency (pnlPct/100 x notional). Losing metrics are positive-abs, consistent with grossLoss.

lossTrades()

Returns the count of trades closed at a loss so far, as a running series.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(lossTrades(), "Kaybeden")

Plots cumulative losing-trade count.

marginLiquidationPrice()

Margin liquidation price for a leveraged position: long -> entry x (1 - 1/leverage), short -> entry x (1 + 1/leverage). Empty when unleveraged (1x) or flat.

NOTE

Derived from the recorded per-bar position size (running max) / same formula used for liquidation.

maxConsecLossDays(n)

Returns nothing. After n consecutive losing days, the open position closes and the strategy halts permanently.

n
number
Consecutive losing-day limit.
NOTE

A day counts as losing if its closing equity is lower than its starting equity. Once the limit is breached, the effect is permanent — the strategy will not open another position for the rest of that run.

CODESCRIPT
maxConsecLossDays(2)
enterLong(true)

After 2 consecutive losing days, the position closes and the strategy stops entering again.

maxContractsHeldAll()

Highest number of contracts held so far (either direction, absolute).

NOTE

Derived from the recorded per-bar position size (running max) / same formula used for liquidation.

maxContractsHeldLong()

Highest number of LONG contracts held so far.

NOTE

Derived from the recorded per-bar position size (running max) / same formula used for liquidation.

maxContractsHeldShort()

Highest number of SHORT contracts held so far.

NOTE

Derived from the recorded per-bar position size (running max) / same formula used for liquidation.

maxDrawdownRisk(miktar, tip)

Returns nothing. When the drawdown exceeds this limit, the open position closes and the strategy halts permanently.

miktar
number
Maximum allowed drawdown.
tip
string
strategy.percent_of_equity (percent of peak equity, default) or strategy.cash (absolute amount).
NOTE

Once the limit is breached, the effect is permanent — the strategy will not open another position for the rest of that run. The drawdown is measured from the strategy's own PEAK equity, not from the entry price — it can trigger even while the position is still profitable relative to entry, if equity has pulled back this much from its own high.

CODESCRIPT
maxDrawdownRisk(10, strategy.percent_of_equity)
enterLong(true)

Even if the position is still profitable relative to entry, when equity falls 10% from its own peak the position closes and the strategy stops entering again.

maxIntradayFilledOrders(n)

Returns nothing. After n orders fill within the day, the open position closes and no new entry is allowed for the rest of that day.

n
number
Intraday filled-order limit.
NOTE

Intended to limit excessive trading frequency. The limit resets at the next UTC day boundary.

CODESCRIPT
maxIntradayFilledOrders(3)
enterLong(barIndex % 2 == 0)
enterShort(barIndex % 2 == 1)

When the 3rd order fills that day, the position closes; no new entry opens for the rest of that day.

maxIntradayLoss(miktar, tip)

Returns nothing. When the intraday loss exceeds this limit, the open position closes and no new entry is allowed for the rest of that day.

miktar
number
Maximum allowed intraday loss.
tip
string
strategy.percent_of_equity (percent of the day's starting equity, default) or strategy.cash (absolute amount).
NOTE

The restriction applies only for that day; it resets at the next UTC day boundary and the strategy resumes normal operation.

CODESCRIPT
maxIntradayLoss(5, strategy.percent_of_equity)
enterLong(true)

When 5% of equity is lost within the day, the position closes; the limit resets the next day.

maxPositionSize(adet)

Returns nothing. In fixed/cash mode (defaultEntryQty or sizeByCash) it caps the maximum reachable size; an order exceeding it is reduced to the cap.

adet
number
Maximum allowed position size (contracts/shares).
NOTE

Meaningful only alongside quantity-based sizing (defaultEntryQty/sizeByCash). In the default %equity mode there is no contract notion, so it has no effect and emits a warning when called.

CODESCRIPT
defaultEntryQty(5)
maxPositionSize(2)
enterLong(crossover(close, sma(close, 20)))
exit(crossunder(close, sma(close, 20)))
plot(close)

Although 5 units are requested, the position opens up to at most 2 units (reduced to the cap).

netPnl()

Returns the net profit/loss series: equity − initial capital.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(netPnl(), "Net K/Z")

Plots cumulative net profit/loss.

openTradeCapitalHeld()

Capital the open position locks up in the account: notional / leverage. Equals the notional without leverage; one tenth of it at 10x. The notional base matches openTradeProfit. Empty value when flat.

openTradeCommission()

The commission the open trade has paid so far (entry only) — in currency. na if no position is open.

NOTE

Entry commission only (the exit has not happened yet); the sum across all open legs, on remaining size. Slippage excluded.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
plot(openTradeCommission(), "Açık komisyon")

Returns the entry commission the open position has paid so far (na if flat).

openTradeEntryBar()

Returns the open position's entry bar index; na if flat.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(openTradeEntryBar(), "Açık Giriş Barı")

Plots the open position's entry bar index.

openTradeEntryComment()

Open-trade entry comment — NOT tracked; returns empty string.

NOTE

No comment tracking; empty string.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
label(close, openTradeEntryComment())

Returns empty string.

openTradeEntryId()

Open-trade entry id — NOT tracked; returns empty string.

NOTE

No id tracking; empty string.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
label(close, openTradeEntryId())

Returns empty string.

openTradeEntryPrice()

Returns the open position's entry price; na if flat.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(openTradeEntryPrice(), "Açık Giriş")

Plots the open position's entry price.

openTradeEntryTime()

Returns the open position's entry time (epoch ms); na if flat.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(openTradeEntryTime(), "Açık Giriş Zamanı")

Plots the open position's entry time.

openTradeMaxDrawdown()

The open trade's worst drawdown so far (MAE) — in currency. na if no position is open.

NOTE

Pure price movement: commission/carry EXCLUDED. A running 'worst so far' value over the open position; the current bar's low/high is included. Leverage/margin included. NOT 100% identical to TradingView.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
plot(openTradeMaxDrawdown(), "Açık MAE")

Returns the open position's worst drawdown so far, in currency (na if flat).

openTradeMaxDrawdownPercent()

The open trade's worst drawdown so far (MAE) — percent. na if no position is open.

NOTE

Pure price movement: commission/carry EXCLUDED. A running 'worst' percent over the open position; the current bar's low/high is included. Leverage included (same scale as P&L percent). NOT 100% identical to TradingView.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
plot(openTradeMaxDrawdownPercent(), "Açık MAE %")

Returns the open position's worst drawdown percent so far (na if flat).

openTradeMaxRunup()

The open trade's best run-up so far (MFE) — in currency. na if no position is open.

NOTE

Pure price movement: commission/carry EXCLUDED. A running 'best so far' value over the open position; the current bar's high/low is included. Leverage/margin included. NOT 100% identical to TradingView.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
plot(openTradeMaxRunup(), "Açık MFE")

Returns the open position's best run-up so far, in currency (na if flat).

openTradeMaxRunupPercent()

The open trade's best run-up so far (MFE) — percent. na if no position is open.

NOTE

Pure price movement: commission/carry EXCLUDED. A running 'best' percent over the open position; the current bar's high/low is included. Leverage included (same scale as P&L percent). NOT 100% identical to TradingView.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
plot(openTradeMaxRunupPercent(), "Açık MFE %")

Returns the open position's best run-up percent so far (na if flat).

openTradeProfit()

Returns the open position's unrealized profit/loss in CURRENCY (unrealized% × initial / 100); na if flat.

NOTE

For percent use `openTradeProfitPercent()`.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(openTradeProfit(), "Açık K/Z")

Plots the open position's currency unrealized P/L.

openTradeProfitPercent()

Returns the open position's unrealized profit/loss as a PERCENT; na if flat.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(openTradeProfitPercent(), "Açık %")

Plots the open position's percent unrealized P/L.

openTradeSize()

Returns the open position's direction: +1 long, −1 short, 0 flat.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(openTradeSize(), "Açık Yön")

Plots the open position's direction.

openTradesCount()

Returns the open-trade count: 1 if a position is open, 0 if flat.

NOTE

At most one open trade is modeled (not broken out by pyramiding levels).

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(openTradesCount(), "Açık İşlem")

Plots whether a position is open (1/0).

openTradesFirstIndex()

First index of the open trade list. Trade history is never trimmed here (no cap), so it always returns 0. Provided so that `for i = openTradesFirstIndex() to...` loops ported from referans dil keep working.

order(koşul, yön?)

Returns nothing; identical to `entryMarket` — routes a market order on the true bar.

koşul
bool
Enters a position with a market order on bars where this is true.
yön
string
Optional. "short"/false → short; otherwise long (default long).
NOTE

Alias of `entryMarket`. Both call the same core (enterLong/enterShort).

CODESCRIPT
order(crossover(close, sma(close, 20)))

A long market order on the crossover bar.

position()

Position direction per bar: +1 long, -1 short, 0 flat.

NOTE

Gives only the DIRECTION (not the size). For size/entry portions, use positionSize.

CODESCRIPT
enterLong(crossover(close,sma(close,20)))
exit(crossunder(close,sma(close,20)))
barcolor(iff(position() > 0, "#26a69a", na))

Candles are green on bars where a long is held; flat bars are not colored.

CODESCRIPT
enterLong(crossover(close,sma(close,20)))
plot(position(), "yön", "#ff9800")

A stepped direction line ranging between 0 and +1 in the lower pane.

positionAvg()

Returns the average entry price of the open position; na when flat.

NOTE

Returns na when flat — guard with `position() != 0` before use.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(positionAvg(), "Giriş Fiyatı")

Plots the open position's entry price.

positionSize()

Direction × the summed remaining size of the open entry parts (may be fractional).

NOTE

While position() gives only direction, positionSize reflects the number of open entry portions and partial closes: 3 entry portions → +3, +2.5 after a 50% close.

CODESCRIPT
pyramiding(3)
enterLong(rsi(close,14)<40, id='L')
exit(rsi(close,14)>60)
plot(positionSize(), "boyut", "#2962ff")

Steps in the lower pane: +1→+2→+3, 0 on exit.

CODESCRIPT
enterLong(barIndex==0, id='L')
exit(barIndex==10, fromEntry='L', qtyPct=50)
plot(positionSize(), "kalan", "#2962ff")
exit(barIndex==40)

50% partial exit on bar 10 → size drops from +1 to +0.5.

runupPct()

Returns the run-up from the running equity trough as a percentage.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(runupPct(), "Yükseliş %")

Plots the running run-up percentage.

scan(condition, title?, score?, note?)

Does not return a value; if the condition is met on the last bar, it produces a scan row.

condition
bool
Produces a scan row if satisfied on the last bar.
title
string
Optional. Title of the scan row.
score
number
Optional. Score used for ranking.
note
string
Optional. Additional note.
NOTE

v0.1: run output only; the scanner/persistent record will be connected in a later phase.

tradeBars(n)

Returns how many bars the n-th closed trade lasted.

n
number
0-based index of the closed trade; negative counts from the end (default 0).
CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(tradeBars(0), "Bar Süresi")

Plots the first trade's bar duration.

tradeCount()

Returns the total number of closed trades (scalar).

NOTE

`closedTradesCount()` is an alias. Not a series — the running total count.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(tradeCount(), "İşlem Sayısı")

Plots the number of trades closed so far.

tradeEntryPrice(n)

Returns the entry price of the n-th closed trade.

n
number
0-based index of the closed trade; negative counts from the end (default 0).
CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(tradeEntryPrice(0), "İlk Giriş")

Plots the first closed trade's entry price.

tradeEntryTime(n)

Returns the entry time (epoch ms) of the n-th closed trade.

n
number
0-based index of the closed trade; negative counts from the end (default 0).
CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(tradeEntryTime(0), "Giriş Zamanı")

Plots the first trade's entry time.

tradeExitPrice(n)

Returns the exit price of the n-th closed trade.

n
number
0-based index of the closed trade; negative counts from the end (default 0).
CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(tradeExitPrice(0), "İlk Çıkış")

Plots the first closed trade's exit price.

tradeExitTime(n)

Returns the exit time (epoch ms) of the n-th closed trade.

n
number
0-based index of the closed trade; negative counts from the end (default 0).
CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(tradeExitTime(0), "Çıkış Zamanı")

Plots the first trade's exit time.

tradeProfit(n)

Returns the n-th closed trade's profit/loss as a PERCENT (pnl%).

n
number
0-based index of the closed trade; negative counts from the end (default Birim YÜZDEDİR (para değil). Para cinsi için `closedTradeProfit(n)`.).
NOTE

The unit is PERCENT (not currency). For currency use `closedTradeProfit(n)`.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(tradeProfit(0), "İlk K/Z %")

Plots the first trade's percent P/L.

tradeSize(n)

Returns the direction/size of the n-th closed trade.

n
number
0-based index of the closed trade; negative counts from the end (default 0).
CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(tradeSize(0), "Yön")

Plots the first trade's direction.

winTrades()

Returns the count of trades closed at a profit so far, as a running series.

CODESCRIPT
enterLong(crossover(close, sma(close, 10)))
exit(crossunder(close, sma(close, 10)))
plot(winTrades(), "Kazanan")

Plots cumulative winning-trade count.