# Deepwick Script

Deepwick Script は Deepwick のチャートとバックテストの言語です。Pine Script v5/v6 の
**一部**です: `ta.*`、`math.*`、`str.*`、`array.*`、`map.*`、`input.*`、`plot*`、`strategy.*`
の呼び出しの多くは Pine と同じように動きます。Deepwick は TradingView とは提携せず、
Pine Script は TradingView, Inc. の商標です。

スクリプトは一番古いバーから一番新しいバーまで、1 バーに 1 回実行され、各変数は履歴を
保持します。Pine と同じ系列のセマンティクスです。

## コードを生成するときに効くルール

- **書く前に未対応のリストを確認してください。** 未対応の呼び出しがここでの一番高額な間違いです。多くはコンパイルが通り、黙って `na` を返すので、正しく見えるスクリプトが何も描かないまま終わります。
- **`request.security()` はチャートの銘柄自身の上位時間足で動きます。** `request.security(syminfo.tickerid, "240", close)` は最後に閉じた 4 時間足的終値を返し、expression は ta.* の呼び出しでもかまいません。別の**銘柄**は na を返します。エンジンはチャートのバーしか持っておらず、別の銘柄は取得しません。
- **先読みはありません。** バックテストのブローカーが未来のデータで注文を約定することはありません。成行注文は*次のバーの始値*で約定します。
- **コストは現実です。** 約定ごとに `strategy()` で宣言した通りの手数料とスリッページが課金されます。コストがゼロでも利益が出る戦略も、それらが>|| 入れると利益が出なくなることがあります。
- **ストップとリミットはバーの流れに従います。** 始値、始値に近い方の極値、もう一方の極値、終値。価格がギャップで飛び越えた注文は始値で約定します。
- **宣言は `=`、再代入は `:=`。** obar をまたいで保持すべき状態には `var` を使ってください。
- **インデントは 4 スペースです。** Pine に波括弧はありません。`if`/`for`/`while`/`switch` の本体はインデントしたブロックです。
- **名前付き引数は最後に置きます。** `name=` と書いた瞬間から、後続の引数もすべて名前付きである必要があります。`plotshape(series=x, title="t", style=shape.circle)` は有効ですが、`plotshape(x, "t", style=…)` は駄目です。名前付きの後に位置引数を混ぜると構文エラーでスクリプトが止まります。
- **決済注文は、それを出した桁では発動できません。** 成行 `strategy.entry` は*次の桁の始値*で約定するので、その桁に書いた `strategy.exit` は次の桁からしか約定されません。出した桁で既にストップを抜いている価格は、执行されません。
- **2 段の決済は一度しか発動しません。** `strategy.exit(stop=…, limit=…)` の片，成交すると他方は一緒に取り消されます。1 回の取引であり、2 回ではありません。バーが両方の水準に到達した場合、バーの流れで先に到達した方が勝ちます。
- **トレーリングストップ:** `strategy.exit(trail_points=N, trail_offset=M)`。どちらも価格単位ではなく**ティック**です。`trail_offset` はストップが働くまでに確保しておくべき利益（ティック）、`trail_points` は最高値から保持する距離です。ストップはあなたに有利にだけ動き、閉じたバーでしか動きません。

## 関数リファレンス

シグネチャと各関数の役割。引数は書いた順です。

### 言語

Deepwick Script は Pine Script の一部（enum、用户定義型、メソッド、map）を実行します。//@version の行は検証されません。スクリプトは一番古いバーから一番新しいバーまで、1 バーに 1 回実行され、各変数は履歴を保持します。

- `x = expr / x := expr` — 変数を宣言し、:= で再代入します。名前の前に任意の型（int、float、bool、string、color、series、simple、const、line、label）を書けます。
- `var / varip` — 最初のバーで一度だけ初期化し、以降のバーでも値を保ちます。スクリプトは閉じたバーで実行されるので、varip は var と同じ挙動になります。
- `x[n]` — 履歴演算子：n 本前の x の値（最初のバーより前では na）。
- `if / else` — 条件分岐のブロック。インデントは 4 スペースです。if は式としても使えます。
- `cond ? a : b` — 三項演算子。
- `switch` — 複数分岐。比較する値を指定する形かどうかは任意です。
- `for i = a to b [by step]` — 回数の指定があるループ。break と continue を使えます。
- `while cond` — 条件が成り立つ間繰り返すループ。
- `f(x, y) => expr` — 用户定義の関数。1 行で書くことも、インデントしたブロックで最後の式を返す形でもかまいません。Pine と同じく、呼び出し位置ごとに ta.* の状態は独立しています。
- `[a, b] = f()` — タプル：関数は複数の値を返せます。ta.macd() や ta.bb() といった組み込み関数も複数値を返します。
- `and / or / not` — 論理演算子。算術：+ - * / %；比較：== != < <= > >=。

### 宣言

- `indicator(title, shorttitle, overlay, precision)` (study) — インジケーターを宣言します。チャートに描画するだけで、バックテストする対象はありません。study() は別名として受け付けられます。
- `strategy(title, overlay, initial_capital, default_qty_type, default_qty_value, commission_type, commission_value, slippage, pyramiding)` — 戦略を宣言します。初期値：initial_capital 100000、注文ごとに 1 枚、手数料 0、slippage 0 ティック、 pyramiding 1。process_orders_on_close などの他の引数は無視されます。

### 入力

入力はエディターの横とインジケーターの設定に表示されるので、コードを触らずに値を変えられます。

- `input.int(defval, title, minval, maxval, step)` — 整数。
- `input.float(defval, title, minval, maxval, step)` — 小数。
- `input.bool(defval, title)` — チェックボックス。
- `input.string(defval, title, options)` — テキスト、または選択肢のリスト。
- `input.session(defval, title)` — "0930-1600" のような取引セッション、または "23456" のような曜日。session.ismarket() やほかの session.* の判定に渡します。
- `input.source(defval, title)` — 価格ソース：open、high、low、close、hl2、hlc3、ohlc4、hlcc4。
- `input.color(defval, title)` — カラーピッカー。
- `input(defval, title)` — 汎用入力。型は初期値から決まります。

### バーデータと時刻

時刻は UTC のミリ秒です。hour() とほかの時刻関数は任意の時刻を受け取ります。hour() はさらに、固定的オフセット一覧から選んだタイムゾーンも受け取ります。夏時間は考慮しません。

- `open, high, low, close, volume` (open, high, low, close, volume) — 現在のバーの価格と出来高。
- `hl2, hlc3, ohlc4, hlcc4` (hl2, hlc3, ohlc4, hlcc4) — 代表的な価格の平均。
- `bar_index, last_bar_index` (bar_index, last_bar_index) — 現在のバーのインデックス（0 が一番古い）と、最後のバーのインデックス。
- `time, time_close` (time, time_close) — バーの始値時刻と終値時刻。関数として — time("D")、time(timeframe.period, "0000-0900:23456", "UTC") — は、このバーを含む上位時間足の開始（または終了）時刻を返し、バーがセッション外なら na を返します。セッション："HHMM-HHMM"、日付をまたぐものも可、カンマ区切りの複数の窓、コロン後ろの曜日は任意（1 = 日曜 … 7 = 土曜）、"24x7"。
- `timeframe.change(timeframe)` — 新しい期間ごとの最初のバーで true になります。例：timeframe.change("D") は毎日最初のバーで true（週は月曜から）。
- `timestamp(timezone?, year, month, day, hour, minute, second)` — 各要素からミリ秒の時刻を作る、または日付文字列から作る：timestamp("2026-01-05T09:30:00Z")。
- `dayofweek.sunday … dayofweek.saturday` (dayofweek.monday, dayofweek.tuesday, dayofweek.wednesday, dayofweek.thursday, dayofweek.friday, dayofweek.saturday) — dayofweek（1 … 7）と比較するための曜日定数。
- `session.ismarket, isfirstbar, islastbar, ispremarket, ispostmarket` (session.ismarket, session.isfirstbar, session.islastbar, session.ispremarket, session.ispostmarket) — セッションの状態。ここの市場は終日取引されるので、すべてのバーが取引セッションに属します。isfirstbar / islastbar は各 UTC 日の最初と最後のバーを示します。
- `year, month, weekofyear, dayofmonth, dayofweek, hour, minute, second` (year, month, weekofyear, dayofmonth, dayofweek, hour, minute, second) — バーの時刻のカレンダー要素。時刻を指定して呼ぶこともできます（例：hour(time, "America/New_York")）。dayofweek：1 = 日曜 … 7 = 土曜。
- `barstate.isfirst, islast, isnew, isconfirmed, ishistory, isrealtime` (barstate.isfirst, barstate.islast, barstate.isnew, barstate.isconfirmed, barstate.ishistory, barstate.isrealtime) — スクリプトがバー履歴のどこに位置しているか。
- `timeframe.period, multiplier, isintraday, isdaily, isweekly, ismonthly` (timeframe.period, timeframe.multiplier, timeframe.isintraday, timeframe.isdaily, timeframe.isweekly, timeframe.ismonthly) — チャートの時間足。
- `syminfo.ticker, tickerid, mintick, pointvalue` (syminfo.ticker, syminfo.tickerid, syminfo.mintick, syminfo.pointvalue) — チャートの銘柄、価格刻み、.point の値。

### テクニカル分析（ta.*）

Pine と同じく、呼び出し位置ごとに状態が独立しています。別の行にある 2 つの ta.ema() 呼び出しは、2 つの別々の平均です。バーが十分になるまで結果は na です。

- `ta.sma(source, length)` — 単純移動平均。
- `ta.ema(source, length)` — 指数移動平均。
- `ta.rma(source, length)` — Wilder の移動平均（RSI と ATR が使います）。
- `ta.wma(source, length)` — 加重移動平均。
- `ta.vwma(source, length)` — 出来高加重移動平均。
- `ta.hma(source, length)` — Hull の移動平均。
- `ta.linreg(source, length, offset)` — 線形回帰線の値。
- `ta.vwap(source)` — 出来高加重平均価格。毎日 00:00 UTC でリセットされます。
- `ta.rsi(source, length)` — 相対力指数（RSI）、0 から 100。
- `ta.macd(source, fastlen, slowlen, siglen)` — [macd, signal, histogram] を返します。
- `ta.stoch(source, high, low, length)` — ストキャスティクス %K、0 から 100。
- `ta.cci(source, length)` — commodity チャンネル指数（CCI）。
- `ta.mfi(series, length)` — 資金フロー指数（MFI）。
- `ta.wpr(length)` — Williams %R、-100 から 0。
- `ta.dmi(diLength, adxSmoothing)` — [+DI, -DI, ADX] を返します。
- `ta.supertrend(factor, atrPeriod)` — [supertrend, direction] を返します。direction は上昇トレンドで -1、下落トレンドで 1 です。
- `ta.sar(start, inc, max)` — パラボリック SAR。
- `ta.mom(source, length)` — モメンタム：source から length 本前の source を引いた値。
- `ta.roc(source, length)` — 変化率（パーセント）。
- `ta.change(source, length)` — length 本前との差（既定は 1）。
- `ta.tr / ta.tr(handle_na)` — 真値幅（True Range）。
- `ta.atr(length)` — 真値幅の平均（Wilder）。
- `ta.bb(series, length, mult)` — Bollinger バンド：[middle, upper, lower] を返します。
- `ta.bbw(series, length, mult)` — Bollinger バンド幅：(upper - lower) / middle。
- `ta.kc(series, length, mult)` — Keltner チャンネル：[middle, upper, lower] を返します。真値幅の EMA を使います。
- `ta.stdev(source, length, biased)` — 標準偏差。
- `ta.variance(source, length, biased)` — 分散。
- `ta.dev(source, length)` — 平均絶対偏差。
- `ta.median(source, length)` — 中央値。
- `ta.highest(source, length) / ta.highest(length)` — 直近 length 本の最高値（既定は high）。
- `ta.lowest(source, length) / ta.lowest(length)` — 直近 length 本の最低値（既定は low）。
- `ta.highestbars(source, length)` — 最高値からのオフセット：0 または負の数。
- `ta.lowestbars(source, length)` — 最低値からのオフセット：0 または負の数。
- `ta.rising(source, length)` — source が前の length 本のどの値よりも上なら true。
- `ta.falling(source, length)` — source が前の length 本のどの値よりも下なら true。
- `ta.crossover(source1, source2)` — source1 が source2 を上へ_cross したバーで true。
- `ta.crossunder(source1, source2)` — source1 が source2 を下に_crossしたバーで true。
- `ta.cross(source1, source2)` — どちらの方向のクロスでも true。
- `ta.pivothigh(source, leftbars, rightbars)` — Pivot high の価格。Pivot の rightbars 本後に確定し、それ以外は na。source は任意（既定は high）。
- `ta.pivotlow(source, leftbars, rightbars)` — Pivot low の価格。Pivot の rightbars 本後に確定し、それ以外は na。source は任意（既定は low）。
- `ta.valuewhen(condition, source, occurrence)` — condition が true だった直近 occurrence 番目のバーにおける source の値。
- `ta.barssince(condition)` — condition が最後に true になってからのバー数。
- `ta.cum(source)` — 最初のバーからの累計。

### 戦略（strategy.*）

成行注文は次のバーの始値で約定します。ストップ注文とリミット注文はバーの流れに沿って約定します：始値 → 始値に近い方の極値 → もう一方の極値 → 終値。価格が注文を飛び越えてギャップすると、始値で約定します。手数料はすべての約定で発生し、slippage は成行とストップの約定に適用されます。

- `strategy.entry(id, direction, qty, limit, stop, comment)` — ポジションを開く、またはポジションを増やす注文。limit や stop を指定しない場合は成行注文です。
- `strategy.order(id, direction, qty, limit, stop, comment)` — strategy.entry() と同じ引数です。
- `strategy.exit(id, from_entry, qty_percent, profit, limit, loss, stop, trail_points, trail_offset, comment)` — エントリーの利益確定、損切り、トレーリングストップ：利益と損失はティック数、limit と stop は価格。trail_points は最高値からのティック距離、trail_offset はトレーリングストップが効くまでに確保しておくべき利益（ティック数）です。ストップはあなたに有利な方向にしか動かず、「閉じた」バーでしか動かないので、バー自身の高値が設定したストップを、そのバー自身が約定することはありません。
- `strategy.close(id, comment, qty_percent)` — エントリーを次のバーの成行で決済します。
- `strategy.close_all(comment)` — すべてのオープンポジションを決済します。
- `strategy.cancel(id) / strategy.cancel_all()` (strategy.cancel_all) — 未約定の注文を取り消します。
- `strategy.position_size, position_avg_price` (strategy.position_size, strategy.position_avg_price) — 現在のポジション（ロングなら正、ショートなら負）と平均価格。
- `strategy.opentrades.entry_bar_index(n), entry_price, entry_time, entry_id, size, profit, commission, max_runup, max_drawdown` (strategy.opentrades.entry_price, strategy.opentrades.entry_time, strategy.opentrades.entry_id, strategy.opentrades.size, strategy.opentrades.profit, strategy.opentrades.commission, strategy.opentrades.max_runup, strategy.opentrades.max_drawdown) — オープン中の取引 n の詳細（0 が一番古い）。該当なしなら na。ショートでは size が負になります。例：10 本後に決済するには bar_index - strategy.opentrades.entry_bar_index(0) >= 10。
- `strategy.closedtrades.entry_bar_index(n), exit_bar_index, entry_price, exit_price, entry_time, exit_time, entry_id, size, profit, commission, max_runup, max_drawdown` (strategy.closedtrades.exit_bar_index, strategy.closedtrades.entry_price, strategy.closedtrades.exit_price, strategy.closedtrades.entry_time, strategy.closedtrades.exit_time, strategy.closedtrades.entry_id, strategy.closedtrades.size, strategy.closedtrades.profit, strategy.closedtrades.commission, strategy.closedtrades.max_runup, strategy.closedtrades.max_drawdown) — 決済済み取引 n の詳細（0 が一番古い。最後は strategy.closedtrades - 1）。
- `strategy.equity, netprofit, openprofit, grossprofit, grossloss, initial_capital` (strategy.equity, strategy.netprofit, strategy.openprofit, strategy.grossprofit, strategy.grossloss, strategy.initial_capital) — 口座の数値。
- `strategy.closedtrades, opentrades, wintrades, losstrades` (strategy.closedtrades, strategy.opentrades, strategy.wintrades, strategy.losstrades) — 取引件数。
- `strategy.long, strategy.short` (strategy.long, strategy.short) — 方向。
- `strategy.fixed, strategy.cash, strategy.percent_of_equity` (strategy.fixed, strategy.cash, strategy.percent_of_equity) — default_qty_type の値。
- `strategy.commission.percent, cash_per_order, cash_per_contract` (strategy.commission.percent, strategy.commission.cash_per_order, strategy.commission.cash_per_contract) — commission_type の値。

### プロットとアラート

- `plot(series, title, color, linewidth, style)` — チャート上、または専用ペインに系列を描画します。
- `plotshape(series, title, style, location, color, text)` — series が true のバーに図形を描画します。
- `plotchar(series, title, char, location, color)` — series が true のバーに文字を描画します。
- `hline(price, title, color, linestyle)` — 固定レベルの水平線。
- `fill(plot1, plot2, color)` — 2 つのプロット、または 2 本の hlines の間を塗ります。
- `bgcolor(color)` — バーの背景を塗ります。
- `barcolor(color)` — バー自体を塗ります。
- `alertcondition(condition, title, message)` — メール、Telegram、Discord、webhook のアラートに変換できる条件を宣言します。
- `plot.style_*` (plot.style_line, plot.style_linebr, plot.style_stepline, plot.style_histogram, plot.style_columns, plot.style_circles, plot.style_cross, plot.style_area) — line、linebr、stepline、histogram、columns、circles、cross、area。
- `hline.style_*` (hline.style_solid, hline.style_dashed, hline.style_dotted) — solid、dashed、dotted。
- `shape.*` (shape.triangleup, shape.triangledown, shape.arrowup, shape.arrowdown, shape.circle, shape.xcross, shape.cross, shape.diamond, shape.square, shape.flag, shape.labelup, shape.labeldown) — triangleup, triangledown, arrowup, arrowdown, circle, xcross, cross, diamond, square, flag, labelup, labeldown.
- `location.*` (location.abovebar, location.belowbar, location.top, location.bottom, location.absolute) — abovebar、belowbar、top、bottom、absolute。
- `size.*` (size.auto, size.tiny, size.small, size.normal, size.large, size.huge) — auto、tiny、small、normal、large、huge。受け付けられますが、図形のサイズは 1 種類だけです。

### 線とボックス

- `line.new(x1, y1, x2, y2, extend, color, style, width)` — 2 つのバーインデックスと価格の間に線を描画し、その id を返します。
- `line.set_x1, set_y1, set_x2, set_y2, set_xy1, set_xy2, set_color, set_style, set_width` (line.set_x1, line.set_y1, line.set_x2, line.set_y2, line.set_xy1, line.set_xy2, line.set_color, line.set_style, line.set_width) — 線を変更します。
- `line.delete(id)` — 線を削除します。
- `box.new(left, top, right, bottom, border_color, bgcolor, extend)` — 長方形を描画し、その id を返します。
- `box.set_left, set_top, set_right, set_bottom, set_bgcolor, set_border_color, set_extend` (box.set_left, box.set_top, box.set_right, box.set_bottom, box.set_bgcolor, box.set_border_color, box.set_extend) — ボックスを変更します。
- `box.delete(id)` — ボックスを削除します。
- `line.style_*, box.style_*` (line.style_solid, line.style_dashed, line.style_dotted, box.style_solid, box.style_dashed, box.style_dotted) — solid、dashed、dotted。
- `extend.*` (extend.none, extend.left, extend.right, extend.both) — none、left、right、both。

### 数学、文字列、色

- `math.abs, ceil, floor, round(number, precision), sign, sqrt, exp, log, log10, pow(base, exponent)` (math.abs, math.ceil, math.floor, math.round, math.sign, math.sqrt, math.exp, math.log, math.log10, math.pow) — 算術。
- `math.max(...), math.min(...), math.avg(...)` (math.min, math.avg) — 任意の個数の値に対して。
- `math.sum(source, length)` — 直近 length 本の合計。
- `math.pi, math.e` (math.pi, math.e) — 定数。
- `na, na(x), nz(x, replacement), fixnan(x)` (na, nz, fixnan) — 欠損値、それの判定、置換、そして直近の na でない値。
- `int(x), float(x), bool(x)` (float, bool) — 型変換。
- `str.tostring(value, format), str.format(text, ...), str.length(s), str.contains(s, part)` (str.format, str.length, str.contains) — 文字列。str.format は {0}、{1}… を引数で置き換えます。
- `color.new(color, transp), color.rgb(red, green, blue, transp)` (color.rgb) — 色を作ります。透明度は 0 から 100。
- `color.*` (color.red, color.green, color.blue, color.orange, color.yellow, color.purple, color.aqua, color.lime, color.fuchsia, color.teal, color.maroon, color.navy, color.olive, color.gray, color.silver, color.white, color.black) — red, green, blue, orange, yellow, purple, aqua, lime, fuchsia, teal, maroon, navy, olive, gray, silver, white, black.

### 配列（array.*）

- `array.new_float, new_int, new_bool, new_string, new_color, new_line, new_box, new_label, new_table(size)` (array.new_float, array.new_int, array.new_bool, array.new_string, array.new_color, array.new_line, array.new_box, array.new_label, array.new_table) — 配列を作ります。
- `array.get, set, insert, push, pop, shift, unshift` (array.get, array.set, array.insert, array.push, array.pop, array.shift, array.unshift) — 要素を読み書きします。
- `array.size, first, last, sum, avg, min, max, stdev` (array.size, array.first, array.last, array.sum, array.avg, array.min, array.max, array.stdev) — 要素数と統計。

### Map とユーザー定義型

ユーザー定義型と `map.<fn>` コレクションがサポートされています。どちらもトップレベルの宣言で、値のインスタンスメソッドは `obj.method(args...)` の書き方になります。

- `enum Name
    Member
    Member = N
    ...` — トップレベルの enum 宣言。値を書かないメンバーは 0 から自動で増えます。明示的な値は数値でも文字列でも構いません。式のどの位置でも `Name.Member` で参照できます。enum の値は素の数値（または文字列）なので、比較演算子や変換なしの `int()` でもそのまま使えます。
- `type Name
    field1
    field2: int
    field3 = default` — トップレベルのユーザー定義型。フィールドは 1 行に 1 つずつ書きます。`: type` と `= default` の部分は将来互換のために受け付けられますが、まだ検証はされません。`Type.new(arg1, arg2, ...)` で生成し、`instance.field` でフィールドを読みます。
- `m = map.new<int, float>()` (map.new) — 空の map を作ります。型引数 `<K, V>` は受け付けられますが、実行時には無視されます。
- `m = map.put(m, key, value)` (map.put) — キーを設定します。map を返すので、呼び出しを連鎖させたり代入し直したりできます。
- `v = map.get(m, key)` (map.get) — 値を読みます。キーがなければ na を返します。
- `n = map.size(m)` (map.size) — 要素数。
- `keys = map.keys(m), values = map.values(m)` (map.keys, map.values) — キーまたは値を Pine の配列として返します（追加順）。
- `map.contains(m, key), map.remove(m, key)` (map.remove) — 存在判定と削除。どちらも map を返します。

## まだ利用できません

エンジンが知らない関数を呼ぶと、スクリプトは「Unknown function」として行番号と列番号の場所で停止します。

- `label.new(), table.new()`: まだ利用できません。線とボックスは利用できます。
- `import, matrix.*, array.new<type>()`: ライブラリ、行列、型付き配列のコンストラクターはまだ実装されていません。
- `strategy.risk.*`: リスクルール（max_position_size、max_intraday_loss、max_drawdown、allow_entry_in）は未対応です。strategy.exit() のトレーリングストップは対応しているので、trail_points と trail_offset を使ってください。

## 実行できるサンプル

このエンジンでコンパイルできる同梱スクリプト:

**RSI Mean Reversion**

```pine
//@version=5
strategy("RSI Mean Reversion", overlay=false, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10, commission_type=strategy.commission.percent, commission_value=0.1)
len = input.int(14, "RSI length", minval=2)
oversold = input.float(30, "Oversold")
exitLevel = input.float(50, "Exit level")
stopPct = input.float(2, "Stop loss %", minval=0, step=0.1)
tpPct = input.float(6, "Take profit %", minval=0, step=0.1)
if strategy.position_size > 0
    strategy.exit("Risk", stop=stopPct > 0 ? strategy.position_avg_price * (1 - stopPct / 100) : na, limit=tpPct > 0 ? strategy.position_avg_price * (1 + tpPct / 100) : na)
r = ta.rsi(close, len)
if strategy.position_size == 0 and r < oversold
    strategy.entry("Long", strategy.long)
if strategy.position_size > 0 and r > exitLevel
    strategy.close("Long", comment="RSI exit")
plot(r, "RSI", color=color.purple)
hline(oversold, "Oversold", color=color.green)
hline(exitLevel, "Exit", color=color.gray)
```

**MACD Crossover**

```pine
//@version=5
strategy("MACD Crossover", overlay=false, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10, commission_type=strategy.commission.percent, commission_value=0.1)
fast = input.int(12, "Fast", minval=1)
slow = input.int(26, "Slow", minval=2)
sig = input.int(9, "Signal", minval=1)
stopPct = input.float(2, "Stop loss %", minval=0, step=0.1)
tpPct = input.float(6, "Take profit %", minval=0, step=0.1)
if strategy.position_size > 0
    strategy.exit("Risk", stop=stopPct > 0 ? strategy.position_avg_price * (1 - stopPct / 100) : na, limit=tpPct > 0 ? strategy.position_avg_price * (1 + tpPct / 100) : na)
[m, s, h] = ta.macd(close, fast, slow, sig)
if ta.crossover(m, s)
    strategy.entry("Long", strategy.long)
if ta.crossunder(m, s)
    strategy.close("Long", comment="MACD cross")
plot(h, "Histogram", color=h >= 0 ? color.new(color.green, 40) : color.new(color.red, 40), style=plot.style_columns)
plot(m, "MACD", color=color.orange)
plot(s, "Signal", color=color.blue)
```

**Bollinger Bounce**

```pine
//@version=5
strategy("Bollinger Bounce", overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10, commission_type=strategy.commission.percent, commission_value=0.1)
len = input.int(20, "Length", minval=2)
mult = input.float(2, "StdDev", minval=0.5, step=0.1)
stopPct = input.float(2, "Stop loss %", minval=0, step=0.1)
tpPct = input.float(6, "Take profit %", minval=0, step=0.1)
if strategy.position_size > 0
    strategy.exit("Risk", stop=stopPct > 0 ? strategy.position_avg_price * (1 - stopPct / 100) : na, limit=tpPct > 0 ? strategy.position_avg_price * (1 + tpPct / 100) : na)
[basis, upper, lower] = ta.bb(close, len, mult)
if strategy.position_size == 0 and close <= lower
    strategy.entry("Long", strategy.long)
if strategy.position_size > 0 and close >= basis
    strategy.close("Long", comment="Back to mean")
u = plot(upper, "Upper", color=color.blue)
plot(basis, "Basis", color=color.gray)
l = plot(lower, "Lower", color=color.blue)
fill(u, l, color=color.new(color.blue, 92))
```

## Elsewhere

- Human reference: https://deepwick.com/ja/docs/script
- Try a script with no signup: https://deepwick.com/try
