파인스크립트의 전략(strategy)를 사용해서 자동매매하는 방법에 대한 내용입니다.
어느정도 파인스크립트에 대한 기본지식이 필요하니 파인스크립트 기초 를 참고해 주세요.

최신 파인스크립트 v6 기준 설명과 예제는 지표를 전략으로 바꾸는 방법과 손절·익절·트레일링 스탑에서 확인할 수 있습니다. 이 글의 v5 코드를 v6로 옮길 때 달라지는 점은 v6 변경점과 v5 코드 옮기기를 참고해 주세요.

전략(strategy) 스크립트 준비하기

※ 파인스크립트 버전 4 이상에서만 사용가능합니다.(//@version=5)
파인스크립트

 1//@strategy_alert_message {{strategy.order.alert_message}}
 2//@version=5
 3strategy('샘플전략', overlay=true)
 4
 5// Create Indicator's
 6shortSMA = ta.sma(close, 10)
 7longSMA = ta.sma(close, 30)
 8rsi = ta.rsi(close, 14)
 9atr = ta.atr(14)
10
11// Specify crossover conditions
12longCondition = ta.crossover(shortSMA, longSMA)
13shortCondition = ta.crossunder(shortSMA, longSMA)
14
15// Execute trade if condition is True
16if longCondition and rsi > 50
17    stopLoss = low - atr * 2
18    takeProfit = high + atr * 2
19    strategy.entry('long', strategy.long, 100)
20    strategy.exit('exit', 'long', stop=stopLoss, limit=takeProfit)
21
22if shortCondition and rsi < 50
23    stopLoss = high + atr * 2
24    takeProfit = low - atr * 2
25    strategy.entry('short', strategy.short, 100)
26    strategy.exit('exit', 'short', stop=stopLoss, limit=takeProfit)
27
28// Plot Moving Average's to chart
29plot(shortSMA)
30plot(longSMA, color=color.new(color.black, 0))
※ 설명을 위한 샘플입니다.실제 매매에는 사용하지 마세요.

앞으로 수정할 코드는 위의 소스에서 19번째,20번째,25번째,26번째줄입니다.

설명
  • 19번째줄에서 매수진입을 하여 20번째에서 매수청산을 합니다.
  • 25번째줄에서 매도진입을 하여 26번째에서 매도청산을 합니다.

바이빗 거래소 1시간봉 차트의 백테스트 결과입니다.

파인스크립트 전략을 사용하여 자동매매하는 방법 - 화면 2

전략(strategy)에 주문메시지 설정하기

단축 주문메시지를 사용하시면 주문내용을 변경해도 스크립트를 수정하실 필요없습니다.
사용방법은 기존 주문메시지와 동일합니다. 자세한 내용은 단축 주문메시지 사용법 링크를 참고해 주세요.

위의 전략에 맞게 3개의 주문메시지를 작성합니다.(바이빗 테스트넷 기준)

매수용 주문메시지

TVM:{"exchange":"bybit-testnet","account":"*","symbol":"BTC/USD","type":"market","side":"buy","bal_pct":50,"token":"토큰"}:MVT

매도용 주문메시지

TVM:{"exchange":"bybit-testnet","account":"*","symbol":"BTC/USD","type":"market","side":"sell","bal_pct":50,"token":"토큰"}:MVT

청산용 주문메시지

TVM:{"exchange":"bybit-testnet","account":"*","symbol":"BTC/USD","type":"market","side":"close","token":"토큰"}:MVT

위의 주문메시지를 아래와 같이 전략 스크립트에 추가합니다.
 1//@strategy_alert_message {{strategy.order.alert_message}}
 2//@version=5
 3strategy('샘플전략', overlay=true)
 4
 5// Create Indicator's
 6shortSMA = ta.sma(close, 10)
 7longSMA = ta.sma(close, 30)
 8rsi = ta.rsi(close, 14)
 9atr = ta.atr(14)
10
11// Specify crossover conditions
12longCondition = ta.crossover(shortSMA, longSMA)
13shortCondition = ta.crossunder(shortSMA, longSMA)
14
15// Execute trade if condition is True
16if longCondition and rsi > 50
17    stopLoss = low - atr * 2
18    takeProfit = high + atr * 2
19    strategy.entry('long', strategy.long, 100, alert_message='TVM:{"exchange":"bybit-testnet","account":"*","symbol":"BTC/USD","type":"market","side":"buy","bal_pct":50,"token":"토큰"}:MVT')
20    strategy.exit('exit', 'long', stop=stopLoss, limit=takeProfit, alert_message='TVM:{"exchange":"bybit-testnet","account":"*","symbol":"BTC/USD","type":"market","side":"close","token":"토큰"}:MVT')
21
22if shortCondition and rsi < 50
23    stopLoss = high + atr * 2
24    takeProfit = low - atr * 2
25    strategy.entry('short', strategy.short, 100, alert_message='TVM:{"exchange":"bybit-testnet","account":"*","symbol":"BTC/USD","type":"market","side":"sell","bal_pct":50,"token":"토큰"}:MVT')
26    strategy.exit('exit', 'short', stop=stopLoss, limit=takeProfit, alert_message='TVM:{"exchange":"bybit-testnet","account":"*","symbol":"BTC/USD","type":"market","side":"close","token":"토큰"}:MVT')
27
28// Plot Moving Average's to chart
29plot(shortSMA)
30plot(longSMA, color=color.new(color.black, 0))

strategy.entry함수와 strategy.exit함수에 alert_message 속성을 추가한뒤 위의 주문메시지를 설정합니다.
※ 여기서 중요한건 alert_message에 주문메시지를 설정할때 쌍따옴표(")가 아니라 작은따옴표(’)로 감싸야 합니다. 주문메시지 안에 쌍따옴표가 들어 있기 때문입니다. (예) alert_message=‘주문메시지’

얼러트 설정하기

아래와 같이 얼러트를 추가합니다. 메시지란에 {{strategy.order.alert_message}} 이 부분이 꼭 설정되어 있어야 합니다.

파인스크립트 전략을 사용하여 자동매매하는 방법 - 화면 7
※ 4개의 시그널이 발생하지만 얼러트는 하나만 설정하면 됩니다.

자주 하는 실수
  • 얼러트 조건에서 전략 스크립트를 선택했는지 확인해 주세요. 지표를 선택하면 {{strategy.order.alert_message}} 가 동작하지 않습니다.
  • 스크립트나 주문메시지를 수정했다면 얼러트를 다시 만들어야 합니다. 얼러트는 만든 시점의 스크립트로 동작합니다. (단축 주문메시지는 주문 내용만 바꿀 때 얼러트를 다시 만들 필요가 없습니다)
  • 여러 방식의 얼러트 차이는 얼러트 메시지 정리를 참고해 주세요.

[참고] 슈퍼트렌드 지표를 전략으로 수정하여 자동매매 하기