# 撰寫 Pine script

### Study  與 strategy 差別

<https://www.tradingview.com/pine-script-docs/en/v4/Quickstart_guide.html#study-vs-strategy>

```
Study 可以用 conditionAlert 但 strategy 不能
strategy 可以 Backtesting and forwardtesting，study 不能
```

### Pine script strategy會晚一根買賣

<https://www.tradingview.com/pine-script-docs/en/v4/language/Execution_model.html>

原因：<https://www.tradingview.com/script/Bi3j0E8Q-Help-needed-with-strategy-Entry-is-off-by-2-candles/>

<https://www.tradingview.com/pine-script-docs/en/v4/essential/Strategies.html#backtesting-and-forwardtesting>

> 因為一般的策略的cross會在當下時間段如過有交叉就觸發，但stateragy必須要到下一個時間段才能確認上一個時間段是否交叉而觸發

之後改為用study時，可以讓alert使用bar close 即可和strategy的時機點相同。

![](https://1723557554-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M0u4DANKZlZvapfxXsp%2F-M0u4Eqt7bPwno0vfljb%2F-M0u4Tqkr5AB9QY473lK%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202020-01-10%20%E4%B8%8A%E5%8D%889.00.34.png?generation=1582596242788813\&alt=media)

## 使用 alertcondition

<https://www.tradingview.com/pine-script-docs/en/v4/annotations/Alert_conditions.html>

> 記得只能用在 study 不能用在 strategy ，在strategy不會顯示錯誤，也不會出現

```javascript
alertcondition(condition=buy, title='My Strategy1', message='Red and blue have crossed!')
```

之後要去鬧鐘手動設定alert，寫完code後不會自動觸發

### 畫線

<https://www.tradingview.com/pine-script-reference/#fun_plot>

```
plot(sma(close, 3), title='Title', color=#00ffaa)
```

> 使用plot畫線

### 設定commission

```javascript
strategy("My Strategy", overlay=true, commission_type=strategy.commission.percent, commission_value=0.04)
```

> 如果不寫，要自己從圖表的齒輪調整 commission

### 設定策略的時間範圍

<https://www.tradingview.com/script/62hUcP6O-How-To-Set-Backtest-Date-Range/>

```javascript
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

//@version=4
strategy("My Strategy", overlay=true)

start     = timestamp(2019, 1, 1, 00, 00)  // backtest start window
finish    = timestamp(2020, 1, 1, 23, 59)        // backtest finish window
window()  => time >= start and time <= finish ? true : false // create function "within window of time"

sDay = 7
bDay = 12
calculate(x, y) => ema(x, y)

longCondition = crossover(calculate(close, sDay), calculate(close, bDay))
if (longCondition)
    strategy.entry("My Long Entry Id", strategy.long, when = window())

shortCondition = crossunder(calculate(close, sDay), calculate(close, bDay))
if (shortCondition)
    strategy.entry("My Short Entry Id", strategy.short, when = window())
```

## 許多Public Library的 strategy是假的數據

<https://www.tradingview.com/pine-script-docs/en/v4/essential/Context_switching_the_security_function.html#understanding-lookahead>

看到很多的performance大過100%，大部分都是使用security function 獲取未來數據造成repaint

<https://www.youtube.com/watch?v=dAzhR0Ve3PI>

## 止損和止盈

```javascript
float sl_inp = input(5.0, title='Stop Loss %')/100
float tp_inp = input(10.0, title='Take Profit %')/100
stop_level = strategy.position_avg_price * (1 - sl_inp)
take_level = strategy.position_avg_price * (1 + tp_inp)
// === EXECUTION ===
strategy.entry("L", strategy.long, when=buy)
strategy.exit("L", stop=stop_level, limit=take_level)
```

<https://backtest-rookies.com/2018/04/13/tradingview-stop-losses/>

## 獲取其他指標的數據

<https://www.tradingview.com/pine-script-docs/en/v4/essential/Context_switching_the_security_function.html>

```javascript
//@version=4
study("My Script")
l_on = security('BITFINEX:BTCUSDSHORTS', "60", close)
l_off = security('BITFINEX:BTCUSDLONGS', "60", close)
plot(l_on, color=color.red)
plot(l_off, color=color.blue)
```

### 取得當前價格

用close 即可

```go
plot(close)
```

### 高亮選擇時間區間

```javascript
//Based on ChrisMoody's Forex Session Templates Based on EST-New York Time Zone

study(title="Trading hours background highlight UTC based",shorttitle="Trading hours", overlay=true)
timeinrange(res, sess) => time(res, sess) != 0

//Change true to false = You have to turn on, won't show up by default
//****Always use lowercase letters


doEurOpen = input(defval=true, type = bool, title="Euro Open On")
//You can copy and paste these colors. white - silver - gray - maroon - red - purple - fuchsia - green - lime
//   olive - yellow - navy - blue - teal - aqua - orange 

europeSessionStart = #1E90FF

bgcolor(doEurOpen and timeinrange(period, "2200-0010") ? europeSessionStart : na, transp=60)
```

## 引入外部資料 (Quandl)

<https://www.tradingview.com/blog/en/using-quandl-data-in-pine-scripts-17950/>
