S T O C K G A M E P R O

Order-Flow Simulator

Guide: Variables and Auto-Trading

Every variable explained in plain English, with practical notes for beginners.

Quick language tips (applies to all sections below): use if (...) { ... } to run rules, compare numbers with >, <, >=, <=, ===, and combine rules with && (AND) / || (OR). Wrap multiple actions with braces { ... } and place one action per line for clarity. Most variables are numbers; many flags use 1 = true and 0 = false. Percent values are literal (30 means 30%). Use // for comments, and use mem to remember state across candles (for example, track if you already bought).

Looking for full, complex scripts? Visit Auto Code Examples for complete auto‑trading strategies and Indicator Examples for advanced indicator formulas.

Index and Time

These values tell you where you are in the data and help you control timing. They are great for delaying trades until enough candles exist.

t

A normalized progress value from 0 to 1 for the current bar within the session. Think of it as a simple progress bar.

Example: Use t to fade colors over time or delay a rule until t > 0.5.

if (t > 0.5) {
  // later in the session
  hold();
}
i

The index of the current candle in the series (0 is the first candle). In simple terms, this is the candle counter.

Example: Only trade after 50 bars with if (i > 50).

if (i > 50) {
  // enough candles to trade
  buyMarket(1);
}
time

The timestamp bucket of the current candle. Use it to detect when a new candle starts.

Example: Store time in mem to detect a new candle.

if (!mem.lastTime) mem.lastTime = time;
if (time != mem.lastTime) {
  mem.lastTime = time;
  hold();
}

OHLCV

These are the core price and volume values for the current candle. Most indicators and strategies are built from these fields.

open

The price where the candle starts. This is the candle's starting price.

Example: Compare close to open to find green candles.

if (close > open) {
  // green candle
  hold();
}
high

The highest traded price during the candle. This is the top price reached in that bar.

Example: Use high to set a stop above the candle.

const breakout = close > high;
if (breakout) {
  buyMarket(1);
}
low

The lowest traded price during the candle. This is the bottom price reached in that bar.

Example: Use low to detect sell pressure or wick tests.

const breakdown = close < low;
if (breakdown) {
  sellMarket(1);
}
close

The last price in the candle (final price once it closes). Most indicators are built from close.

Example: Check close > ema20 for trend filters.

if (close > ema20) {
  buyMarket(1);
}
vol

Total traded volume in the candle. Higher volume means more participation.

Example: Require vol > volSma20 for confirmation.

if (vol > volSma20) {
  buyMarket(1);
}
prevOpen

Open price of the previous candle. Same idea as open, but one bar ago.

Example: Compare open to prevOpen to see opening drift.

if (open > prevOpen) {
  // higher open
  hold();
}
prevHigh

High price of the previous candle. Same idea as high, but one bar ago.

Example: Use close > prevHigh for breakouts.

if (close > prevHigh) {
  buyMarket(1);
}
prevLow

Low price of the previous candle. Same idea as low, but one bar ago.

Example: Use close < prevLow for breakdowns.

if (close < prevLow) {
  sellMarket(1);
}
prevClose

Close price of the previous candle. Same idea as close, but one bar ago.

Example: Use close - prevClose for momentum.

if (close > prevClose) {
  hold();
}
prevVol

Volume of the previous candle. Same idea as vol, but one bar ago.

Example: Detect a volume spike with vol > prevVol * 1.5.

if (vol > prevVol * 1.5) {
  buyMarket(1);
}
prev2Open

Open price two candles ago. Same idea as open, but two bars back.

Example: Compare open to prev2Open for short-term trend.

if (open > prev2Open) {
  hold();
}
prev2High

High price two candles ago. Same idea as high, but two bars back.

Example: Break above prev2High to confirm momentum.

if (close > prev2High) {
  buyMarket(1);
}
prev2Low

Low price two candles ago. Same idea as low, but two bars back.

Example: Use close < prev2Low as a weakness signal.

if (close < prev2Low) {
  sellMarket(1);
}
prev2Close

Close price two candles ago. Same idea as close, but two bars back.

Example: Use close > prev2Close to confirm upward drift.

if (close > prev2Close) {
  hold();
}
prev2Vol

Volume two candles ago. Same idea as vol, but two bars back.

Example: Compare vol to prev2Vol to spot rising volume.

if (vol > prev2Vol) {
  hold();
}

Candle Structure

Derived candle features explain the candle’s shape. Use them to detect strong closes, rejections, and indecision.

range

High minus low of the candle, showing raw volatility. Bigger range means a bigger move in that candle.

Example: Use range to avoid trading tiny candles.

if (range > atr14) {
  // large candle
  hold();
}
rangePct

Range expressed as a percent of close. This makes small and large prices comparable.

Example: Require rangePct > 0.5 for breakouts.

if (rangePct > 0.5) {
  buyMarket(1);
}
body

The absolute size of the candle body. It is the distance between open and close.

Example: A large body with low wicks can show conviction.

if (body > 0) {
  hold();
}
bodyPct

Body size as a percent of open. This makes body size comparable across prices.

Example: Filter for strong moves with bodyPct > 0.3.

if (bodyPct > 0.3) {
  buyMarket(1);
}
bodyDir

Direction: 1 bullish, -1 bearish. It is a quick up/down flag.

Example: Combine bodyDir with vol for trend bars.

if (bodyDir > 0) {
  hold();
}
isBull

1 if close is above open. Think of it as a green candle flag.

Example: Count consecutive bulls: isBull this bar and previous.

if (isBull === 1) {
  hold();
}
isBear

1 if close is below open. Think of it as a red candle flag.

Example: Use isBear for short filters.

if (isBear === 1) {
  hold();
}
isDoji

1 if body is very small relative to price. Doji often signals indecision.

Example: Avoid entries on isDoji === 1.

if (isDoji === 1) {
  hold();
}
gap

Open minus previous close (positive is gap up). It shows a jump between candles.

Example: Use gap > 0 to detect gap-and-go.

if (gap > 0) {
  buyMarket(1);
}
gapPct

Gap expressed as a percent of previous close. This makes gaps comparable across prices.

Example: Require gapPct > 0.2 for strong gap setups.

if (gapPct > 0.2) {
  buyMarket(1);
}
gapDir

Gap direction: 1 up, -1 down, 0 flat. This is the gap as a simple flag.

Example: Only trade gaps when gapDir === 1.

if (gapDir === 1) {
  hold();
}
upperWick

Size of the upper wick. Big upper wicks can mean price was rejected.

Example: Large upperWick can signal rejection.

if (upperWick > lowerWick) {
  hold();
}
lowerWick

Size of the lower wick. Big lower wicks can mean buying support.

Example: Large lowerWick can signal buying pressure.

if (lowerWick > upperWick) {
  hold();
}
upperWickPct

Upper wick as a percent of range. Percent makes wick size comparable.

Example: Use upperWickPct > 60 to detect rejection.

if (upperWickPct > 60) {
  hold();
}
lowerWickPct

Lower wick as a percent of range. Percent makes wick size comparable.

Example: Use lowerWickPct > 60 for wick-buy signals.

if (lowerWickPct > 60) {
  hold();
}
hlRangePct

High-low range as a percent of close. Good for comparing volatility across prices.

Example: Use hlRangePct to scale stop distance.

if (hlRangePct > 0.6) {
  hold();
}
closePos

Close position in the range (0 bottom to 1 top). Values near 1 mean strong closes.

Example: Use closePos > 0.8 to find strong closes.

if (closePos > 0.8) {
  buyMarket(1);
}
hl2

Midpoint of high and low (H+L)/2. A simple center price for the candle.

Example: Use hl2 as a simple mean price filter.

if (close > hl2) {
  hold();
}
hlc3

Average of high, low, close (H+L+C)/3. A common "typical" price.

Example: Compare close vs hlc3 for bias.

if (close > hlc3) {
  hold();
}
ohlc4

Average of open, high, low, close (O+H+L+C)/4. It smooths the candle even more.

Example: Use ohlc4 in custom smoothing formulas.

if (close > ohlc4) {
  hold();
}
typical

Typical price, same as HLC3. Use it as a simple average price.

Example: Use typical for VWAP-style logic.

if (close > typical) {
  hold();
}

Returns and Range

Return and range values help you measure speed and volatility. They are useful for sizing trades and setting targets.

change

Close minus previous close, the raw price change. Positive means price rose.

Example: change > 0 means the bar closed higher.

if (change > 0) {
  hold();
}
changePct

Percent change versus the previous close. This makes changes comparable across prices.

Example: Use changePct > 0.2 for strong momentum bars.

if (changePct > 0.2) {
  buyMarket(1);
}
logReturn

Log return between closes for smoother stats. It reduces the impact of big jumps.

Example: Average logReturn to estimate drift.

if (logReturn > 0) {
  hold();
}
trueRange

True range that includes gaps between candles. It reflects real movement better than raw range.

Example: Use trueRange to set stops in volatile markets.

if (trueRange > atr14) {
  hold();
}
atr7

ATR over 7 bars, fast volatility. Higher values mean recent candles are larger.

Example: Use atr7 for tight scalping stops.

if (atr7 > atr14) {
  hold();
}
atr14

ATR over 14 bars, standard volatility. Think of it as a typical candle size.

Example: Use atr14 to size positions by risk.

if (atr14 > 0) {
  hold();
}
atr21

ATR over 21 bars, slower volatility. This changes more slowly than atr14.

Example: Use atr21 for swing-style targets.

if (atr21 > atr14) {
  hold();
}
atrPct

ATR as a percent of current price. This helps compare volatility across instruments.

Example: Use atrPct to normalize stops across price levels.

if (atrPct > 1) {
  hold();
}

Moving Averages

Moving averages smooth price. You can use them as trend filters, dynamic support/resistance, or crossover signals.

sma5

SMA of last 5 closes for short trend. Shorter SMAs react faster to price changes.

Example: If close > sma5, short-term bias is up.

if (close > sma5) {
  buyMarket(1);
}
sma10

SMA of last 10 closes for micro trend. It moves faster than longer averages.

Example: Use sma10 as a trailing support level.

if (close > sma10) {
  hold();
}
sma20

SMA of last 20 closes for common trend filter. Many traders use this as a basic trend line.

Example: Trade long only when close > sma20.

if (close > sma20) {
  buyMarket(1);
}
sma50

SMA of last 50 closes for mid trend. It is smoother and slower than sma20.

Example: Use sma50 to avoid counter-trend entries.

if (close > sma50) {
  hold();
}
sma100

SMA of last 100 closes for major trend. This is a very slow, long-term average.

Example: Only trade with direction of sma100.

if (close > sma100) {
  hold();
}
ema5

EMA of last 5 closes, very reactive. EMA responds faster than SMA.

Example: Use ema5 for fast crossover entries.

if (close > ema5) {
  buyMarket(1);
}
ema10

EMA of last 10 closes, fast trend. It reacts quickly to new prices.

Example: Use ema10 to trail stops.

if (close > ema10) {
  hold();
}
ema20

EMA of last 20 closes, common trend line. Many strategies use it as a baseline.

Example: Trade only when price is above ema20.

if (close > ema20) {
  buyMarket(1);
}
ema50

EMA of last 50 closes, mid trend. Smoother and slower than ema20.

Example: Use ema50 for swing confirmation.

if (close > ema50) {
  hold();
}
ema100

EMA of last 100 closes, long trend. It changes very slowly.

Example: Avoid longs if close is below ema100.

if (close > ema100) {
  hold();
}
smaDiff

SMA10 minus SMA20, trend spread. Positive means short-term is above mid-term.

Example: smaDiff > 0 suggests bullish pressure.

if (smaDiff > 0) {
  hold();
}
emaDiff

EMA10 minus EMA20, trend spread. Positive means short-term momentum is higher.

Example: emaDiff turning positive signals trend shift.

if (emaDiff > 0) {
  hold();
}
ema10Slope

Change of EMA10 from previous bar. Positive means EMA10 is rising.

Example: Require ema10Slope > 0 to enter longs.

if (ema10Slope > 0) {
  hold();
}
sma20Slope

Change of SMA20 from previous bar. Positive means the trend line is rising.

Example: If sma20Slope < 0, avoid longs.

if (sma20Slope > 0) {
  hold();
}
priceAboveSma20

1 if close is above SMA20. A simple yes/no trend filter.

Example: Use priceAboveSma20 === 1 as a filter.

if (priceAboveSma20 === 1) {
  hold();
}
priceAboveEma20

1 if close is above EMA20. Another quick yes/no trend check.

Example: Require priceAboveEma20 for trend trades.

if (priceAboveEma20 === 1) {
  hold();
}
trendUp

1 when EMA10 is at or above EMA20, else -1. Think of it as a simple trend direction flag.

Example: trendUp > 0 can enable only long trades.

if (trendUp > 0) {
  hold();
}

Momentum

Momentum indicators show how fast price is moving. Use them to avoid chasing exhausted moves.

rsi7

RSI over 7 periods for fast momentum. Low values suggest oversold, high values suggest overbought.

Example: Buy dips when rsi7 < 20 and trendUp is positive.

if (rsi7 < 30) {
  buyMarket(1);
}
rsi14

Standard 14-period RSI. The most common RSI length used by traders.

Example: Consider selling when rsi14 > 70.

if (rsi14 > 70) {
  sellMarket(1);
}
rsi21

Slow 21-period RSI for smoother trend. It changes more slowly than rsi14.

Example: Use rsi21 > 50 as a trend filter.

if (rsi21 > 50) {
  hold();
}
rsiSlope

Change in RSI14 from previous bar. Positive means RSI is rising.

Example: rsiSlope > 0 can confirm rising momentum.

if (rsiSlope > 0) {
  hold();
}
roc12

Rate of change over 12 bars. Positive means price is higher than 12 bars ago.

Example: roc12 > 0 indicates upward acceleration.

if (roc12 > 0) {
  hold();
}
stochK

Stochastic %K (0-100), position inside recent range. Near 0 is near the low, near 100 is near the high.

Example: Look for stochK < 20 for oversold bounces.

if (stochK < 20) {
  buyMarket(1);
}
stochD

Smoothed Stochastic signal line. It helps reduce noise in %K.

Example: Use stochK crossing above stochD as a trigger.

if (stochK > stochD) {
  hold();
}
macdLine

MACD line, EMA12 minus EMA26. Positive means short-term is above long-term.

Example: macdLine > 0 suggests bullish momentum.

if (macdLine > 0) {
  buyMarket(1);
}
macdSignal

MACD signal line, EMA9 of MACD line. Use it as a smoother comparison line.

Example: Buy when macdLine crosses above macdSignal.

if (macdLine > macdSignal) {
  hold();
}
macdHist

MACD histogram, MACD line minus signal line. Bigger values mean stronger momentum.

Example: Rising macdHist can confirm acceleration.

if (macdHist > 0) {
  hold();
}

Volume and Bands

Volume confirms participation. Bands show volatility expansion or contraction and are useful for mean‑reversion setups.

vwap

Volume weighted average price across the session. Think of it as the session's fair price.

Example: Consider longs when close > vwap.

if (close > vwap) {
  buyMarket(1);
}
obv

On-Balance Volume, cumulative flow based on price direction. Rising OBV can mean buyers are stronger.

Example: Rising obv with flat price can hint accumulation.

if (obv > 0) {
  hold();
}
closeAboveVwap

1 if close is above VWAP, else 0. A simple yes/no filter for VWAP direction.

Example: Combine with trendUp for higher-quality setups.

if (closeAboveVwap === 1) {
  hold();
}
volSma5

Average volume over 5 bars. Use it as a short-term volume baseline.

Example: Use vol > volSma5 to detect strong participation.

if (vol > volSma5) {
  hold();
}
volSma20

Average volume over 20 bars. A common mid-term volume baseline.

Example: Use volRel based on volSma20 for filters.

if (vol > volSma20) {
  hold();
}
volSma50

Average volume over 50 bars. A slower baseline for longer-term activity.

Example: Use volSma50 for long-term volume baseline.

if (vol > volSma50) {
  hold();
}
volChange

Current volume minus previous volume. Positive means activity is rising.

Example: volChange > 0 indicates growing participation.

if (volChange > 0) {
  hold();
}
volChangePct

Percent change of volume versus previous bar. Helps compare volume spikes across bars.

Example: Use volChangePct > 30 for volume spikes.

if (volChangePct > 30) {
  hold();
}
volRel

Volume relative to volSma20 (1.0 is average). Values above 1 mean above-average volume.

Example: Require volRel > 1.2 for breakout confirmation.

if (volRel > 1.2) {
  hold();
}
bbUpper

Upper Bollinger Band (volatility ceiling). Price near this line is relatively high.

Example: If close > bbUpper, volatility expansion may be underway.

if (close > bbUpper) {
  sellMarket(1);
}
bbMiddle

Middle Bollinger Band (the SMA line). It is the center line of the bands.

Example: Use bbMiddle as mean reversion target.

if (close > bbMiddle) {
  hold();
}
bbLower

Lower Bollinger Band (volatility floor). Price near this line is relatively low.

Example: If close < bbLower, price is extended down.

if (close < bbLower) {
  buyMarket(1);
}
bbWidth

Band width, upper minus lower. Bigger width means higher volatility.

Example: Low bbWidth can signal a squeeze.

if (bbWidth < 0.5) {
  hold();
}
bbPctB

Percent-B position inside the bands (0 to 1). 0 is near the lower band, 1 is near the upper.

Example: bbPctB < 0.1 means price is near the lower band.

if (bbPctB < 0.1) {
  buyMarket(1);
}

Arrays and Helpers

Helpers let you compute indicators directly on arrays. This is useful when you want custom logic beyond built‑ins.

data

Array of candle objects for the entire session. Use it to access full history.

Example: Access raw history with data[i - 5].

if (data.length > 10) {
  const last = data[data.length - 1];
  hold();
}
opens

Array of open prices aligned by index. Each item matches the same candle index.

Example: Use opens[i] to compare with current close.

if (opens.length > i) {
  const o = opens[i];
  hold();
}
highs

Array of high prices aligned by index. Think of it as the "high" history list.

Example: Use highest(highs, 20, i) for breakout levels.

if (highs.length > i) {
  const h = highs[i];
  hold();
}
lows

Array of low prices aligned by index. Think of it as the "low" history list.

Example: Use lowest(lows, 20, i) for support levels.

if (lows.length > i) {
  const l = lows[i];
  hold();
}
closes

Array of close prices aligned by index. Most custom calculations use closes.

Example: Use ema(closes, 10, i) inside custom logic.

if (closes.length > i) {
  const c = closes[i];
  hold();
}
vols

Array of volume values aligned by index. Use it to compute volume averages.

Example: Use sma(vols, 20, i) for volume average.

if (vols.length > i) {
  const v = vols[i];
  hold();
}
sma(arr,p,i)

Helper: SMA of arr with period p at index i. Returns null until enough data exists.

Example: sma(closes, 20, i) to compute SMA20 inline.

const sma20 = sma(closes, 20, i);
if (sma20 !== null && close > sma20) {
  buyMarket(1);
}
ema(arr,p,i)

Helper: EMA of arr with period p at index i. It reacts faster than SMA.

Example: ema(closes, 10, i) for custom EMA.

const ema10 = ema(closes, 10, i);
if (ema10 !== null && close > ema10) {
  hold();
}
highest(arr,p,i)

Helper: highest value in the last p points. Useful for breakout levels.

Example: highest(highs, 20, i) for breakouts.

const recentHigh = highest(highs, 20, i);
if (recentHigh !== null && close > recentHigh) {
  buyMarket(1);
}
lowest(arr,p,i)

Helper: lowest value in the last p points. Useful for support levels.

Example: lowest(lows, 20, i) for supports.

const recentLow = lowest(lows, 20, i);
if (recentLow !== null && close < recentLow) {
  sellMarket(1);
}
sum(arr,p,i)

Helper: sum of the last p values. Use it to build custom averages.

Example: sum(vols, 5, i) for recent volume.

const volSum = sum(vols, 5, i);
if (volSum !== null) {
  hold();
}
avg(arr,p,i)

Helper: average of the last p values. A quick mean without writing a loop.

Example: avg(closes, 5, i) for quick mean.

const closeAvg = avg(closes, 5, i);
if (closeAvg !== null && close > closeAvg) {
  hold();
}
std(arr,p,i)

Helper: standard deviation over last p values. Higher values mean more spread.

Example: std(closes, 20, i) for volatility.

const volStd = std(closes, 20, i);
if (volStd !== null) {
  hold();
}

Auto-Trading Variables

These describe your portfolio and last trade. Use them to control risk, position size, and trade frequency.

balance

Cash available for new buys. If this is too low, buys will fail.

Example: Check balance > price * 5 before buying.

if (balance > price * 5) {
  buyMarket(5);
}
holdings

Number of shares currently held. If 0, you have no position.

Example: Use holdings > 0 to allow sells.

if (holdings > 0) {
  hold();
}
avgPrice

Average entry price of your position. Use it to know if you are in profit.

Example: Compute unrealized PnL with (price - avgPrice) * holdings.

if (holdings > 0 && price > avgPrice) {
  hold();
}
price

Alias of the current price (same as close). Use this in order calculations.

Example: Use price to compute limit prices.

if (price > ema20) {
  buyMarket(1);
}
equity

Total account value: cash plus position value. This is your true account size.

Example: Use equity for percent-based sizing.

if (equity > 1000) {
  hold();
}
pnl

Unrealized profit or loss of the current position. Positive means you are up.

Example: If pnl > 50, scale out.

if (pnl > 50) {
  sellPct(50);
}
returnRate

Return percentage versus the starting balance. A quick snapshot of overall performance.

Example: Pause trading if returnRate < -5.

if (returnRate < -5) {
  hold();
}
positionValue

Current position value (holdings * price). This is how much your position is worth now.

Example: Use sellPct(50) to sell half of this value.

if (positionValue > 0) {
  hold();
}
lastTrade

Object with last trade info: type, price, qty, time, kind. Use it to avoid repeating actions.

Example: Use lastTrade.type === 'BUY' to avoid double entries.

if (lastTrade && lastTrade.type === 'BUY') {
  hold();
}

Order Types

Choose the order type based on how urgent the entry/exit is. Market is instant; limit/stop are conditional.

Market

Executes immediately at the current price. Best when speed matters more than price.

Example: Use market orders for instant entries in fast moves.

buyMarket(1);
// immediate execution at current price
Limit

Reserved order that fills only when price crosses the limit. Good for better prices.

Example: Place a limit buy below price to catch pullbacks.

buyLimit(price * 0.995, 2);
// waits until price drops to limit
Stop

Triggers when price crosses a stop level, then executes at market. Often used as a safety exit.

Example: Use a stop sell below price for protection.

sellStop(price * 0.99, 2);
// triggers on stop level
Stop-Limit

Triggers on a stop, then becomes a limit order. Gives price control after the trigger.

Example: Use stop-limit to control slippage on breakouts.

buyStop(price * 1.01, 2, price * 1.015);
// stop triggers then becomes limit

When a limit or stop order fills, you will see a trade log tag like (LIMIT)/(STOP) and a toast message.

Order Helpers (with runnable examples)

Each helper below includes a complete code line you can paste as‑is into auto‑trading logic.

orderQty

Current quantity from the Order Qty input on the trading screen. This mirrors the UI number.

Example: Use the UI quantity directly.

if (orderQty > 0) { buyOrderQty(); }
setOrderQty(qty)

Updates the Order Qty input from code and returns the normalized value. Useful before a buy/sell.

Example: Set UI order size before buying.

setOrderQty(10);
buyOrderQty();
buyOrderQty()

Market buy using the current Order Qty input. It buys exactly what the UI shows.

Example: Buy the UI size on a signal.

if (rsi14 < 30) { buyOrderQty(); }
sellOrderQty()

Market sell using the current Order Qty input. It sells exactly what the UI shows.

Example: Sell the UI size on a signal.

if (holdings > 0 && rsi14 > 70) { sellOrderQty(); }
buy(qty)

Market buy for a fixed quantity. qty is the number of shares.

Example: Buy 3 shares once per bar.

if (oncePerBar('mktBuy')) { buy(3); }
sell(qty)

Market sell for a fixed quantity. qty is the number of shares.

Example: Sell 2 shares if RSI is high.

if (holdings > 0 && rsi14 > 70) { sell(2); }
hold()

No action; useful for clarity in conditions. Think of it as "do nothing."

Example: Use to explicitly do nothing in a branch.

if (trendUp < 0) { hold(); }
buyMarket(qty)

Explicit market buy using the current price. Same as buy(qty) but clearer.

Example: Enter when momentum turns positive.

if (macdHist > 0) { buyMarket(5); }
sellMarket(qty)

Explicit market sell using the current price. Same as sell(qty) but clearer.

Example: Exit when momentum flips negative.

if (holdings > 0 && macdHist < 0) { sellMarket(5); }
buyLimit(price, qty)

Limit buy at or below a target price. The order waits until price hits the limit.

Example: Bid slightly below current price.

if (oncePerBar('bid')) { buyLimit(price * 0.995, 4); }
sellLimit(price, qty)

Limit sell at or above a target price. The order waits until price hits the limit.

Example: Take profit a bit above price.

if (holdings > 0) { sellLimit(price * 1.01, 4); }
buyStop(stop, qty, limitPrice?)

Stop buy that triggers on breakout (optional stop-limit). It activates only after price crosses the stop.

Example: Buy if price breaks higher.

if (trendUp > 0) { buyStop(price * 1.01, 3); }
sellStop(stop, qty, limitPrice?)

Stop sell for protection (optional stop-limit). It activates only after price crosses the stop.

Example: Protect position below price.

if (holdings > 0) { sellStop(price * 0.99, 3); }
buyPct(pct)

Market buy using a percent of equity. Equity means cash plus position value.

Example: Use 25 percent of equity on dips.

if (rsi14 < 30) { buyPct(25); }
sellPct(pct)

Market sell using a percent of position value. 50 means sell half.

Example: Sell half when RSI is high.

if (holdings > 0 && rsi14 > 70) { sellPct(50); }
buyValue(amount)

Market buy using a fixed cash amount. Good for dollar-based sizing.

Example: Buy 250 dollars every 5 seconds.

if (cooldown('val', 5000)) { buyValue(250); }
sellValue(amount)

Market sell a fixed value of holdings. You sell by dollars, not shares.

Example: Sell 200 dollars of position.

if (holdings > 0) { sellValue(200); }
riskQty(opts)

Position sizing by risk percent and stop distance. Helps keep losses consistent.

Example: Risk 1 percent with a 1 percent stop.

const qty = riskQty({ riskPct: 1, stopPct: 1 }); if (qty > 0) buy(qty);
cooldown(key, ms)

Rate-limit actions using a key and milliseconds. Prevents repeated orders too fast.

Example: Avoid spamming entries on every tick.

if (cooldown('entry', 3000)) { buy(1); }
oncePerBar(key)

Runs logic only once per candle. Useful to avoid duplicate orders in the same bar.

Example: Prevent duplicate orders in a single bar.

if (oncePerBar('scale')) { sell(1); }
mem

Persistent memory object for strategy state. Store flags so logic remembers past actions.

Example: Save mode across ticks in mem.mode.

if (!mem.mode) mem.mode = 'trend';
ctx

Context object with timing and bar metadata. Read-only info about the current tick.

Example: Use ctx.tick to run periodic actions.

if (ctx.tick % 20 === 0) { mem.lastPulse = ctx.now; }