
이 글은 이동 평균 교차 원칙에 기반한 정량 거래 전략을 소개한다. 이 전략은 가격과 이동 평균의 관계를 비교하여 다공간 방향을 판단하고, 정지 중지 손실 지점을 설정하면서 위험을 제어한다. 전략 코드는 Pine Script을 사용하여 작성되었으며, Dhan 거래 플랫폼의 API를 통합하여 전략 신호의 자동 거래를 가능하게 한다.
이 전략의 핵심은 이동 평균이며, 일정 주기 동안의 폐가 가격의 간단한 이동 평균을 계산하여 추세를 판단하는 근거로 한다. 가격 상위 지평선을 통과할 때 더 많은 신호가 발생하고, 하위 지평선을 통과할 때 더 많은 신호가 발생한다. 동시에, exrem 함수를 사용하여 필터링 연속 반복 신호를 사용하여 신호 품질을 향상시킨다. 전략은 현재 포지션 방향과 가격과 평균선의 위치 관계에 따라, 그에 따른 중지 손실 가격을 설정하여, 각 거래의 위험과 수익을 제어한다.
이동 평균 경계는 시장의 중기 및 장기 추세를 효과적으로 포착하는 간단한 사용 가능한 트렌드 추적 방법입니다. 합리적인 매개 변수를 설정하여 전략은 트렌드 상황에서 안정적인 수익을 얻을 수 있습니다. 스톱 스톱의 설정은 리스크 수익률을 높여 리스크 수익률을 높여 리스크 수익률을 높이는 데 도움이됩니다. 전략 코드 논리는 명확하고 기능 모듈화, 가독성 및 확장성을 사용하여 강력합니다. 또한 전략은 DhanAPI 플랫폼을 통합하여 신호의 자동화 주문 거래를 구현하고 실행 효율성을 향상시킵니다.
이동 평균은 본질적으로 지연 지표이며, 시장이 변할 때 신호가 지연되어 최적의 거래 시기를 잘못하거나 거짓 신호를 생성 할 수 있습니다. 잘못된 파라미터 설정은 전략의 성과에 영향을 미치며, 다양한 시장 특성과 주기에 따라 최적화가 필요합니다. 고정된 퍼센트 스톱 손실은 시장의 변동률 변화에 적응 할 수 없으며, 잘못된 파라미터 설정으로 손실이 발생할 위험이 있습니다.
이동 평균 경로 전략은 트렌드 추적과 스톱 스톱 손실 통제를 통해 트렌드 상황에서 이익을 얻을 수있는 간단한 실용적인 정량 거래 전략입니다. 그러나 전략 자체에는 일정 한계가 있으며 시장 특성과 위험 선호에 따라 최적화 및 개선이 필요합니다. 실제 응용에서는 엄격한 징계 집행과 위험을 잘 제어하는 데 주의를 기울여야합니다. 전략 프로그래밍은 Pine Script와 같은 전문 언어를 사용하여 거래 플랫폼 API를 통합하여 전략의 자동화 실행을 구현 할 수 있습니다.
/*backtest
start: 2024-05-01 00:00:00
end: 2024-05-31 23:59:59
period: 1h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © syam-mohan-vs @ T7 - wwww.t7wealth.com www.t7trade.com
//This is an educational code done to describe the fundemantals of pine scritpting language and integration with Indian discount broker Dhan. This strategy is not tested or recommended for live trading.
//@version=5
strategy("Pine & Dhan - Moving Average Crossover Strategy", overlay=true)
//Remove excess signals
exrem(condition1, condition2) =>
temp = false
temp := na(temp[1]) ? false : not temp[1] and condition1 ? true : temp[1] and condition2 ? false : temp[1]
ta.change(temp) == true ? true : false
// Define MA period
ma_period = input(20, title = "MA Length")
// Define target and stop loss levels
target_percentage = input.float(title="Target Profit (%)", defval=2.0)
stop_loss_percentage = input.float(title="Stop Loss (%)", defval=1.0)
// Calculate the MA
ma = ta.sma(close, ma_period)
// Entry conditions
long_entry = close >= ma
short_entry = close < ma
// Calculate target and stop loss prices
target_price = long_entry ? strategy.position_avg_price + (close * (target_percentage / 100)) : strategy.position_avg_price - (close * (target_percentage / 100))
stop_loss_price = short_entry ? strategy.position_avg_price + (close * (stop_loss_percentage/ 100)) : strategy.position_avg_price - (close * (stop_loss_percentage / 100))
long_entry := exrem(long_entry,short_entry)
short_entry := exrem(short_entry,long_entry)
// Plot the MA
plot(ma, color=color.blue, linewidth=2, title="MA")
// Plot the entry and exit signals
plotshape(long_entry, style=shape.arrowup, color=color.green, size=size.small,location = location.belowbar)
plotshape(short_entry, style=shape.arrowdown, color=color.red, size=size.small,location = location.abovebar)
//Find absolute value of positon size to exit position properly
size = math.abs(strategy.position_size)
//Replace these four JSON strings with those generated from user Dhan account
long_msg = '{"secret":"C0B2u","alertType":"multi_leg_order","order_legs":[{"transactionType":"B","orderType":"MKT","quantity":"1","exchange":"NSE","symbol":"NIFTY1!","instrument":"FUT","productType":"I","sort_order":"1","price":"0"}]}'
long_exit_msg = '{"secret":"C0B2u","alertType":"multi_leg_order","order_legs":[{"transactionType":"S","orderType":"MKT","quantity":"1","exchange":"NSE","symbol":"NIFTY1!","instrument":"FUT","productType":"M","sort_order":"1","price":"0"}]}'
short_msg = '{"secret":"C0B2u","alertType":"multi_leg_order","order_legs":[{"transactionType":"S","orderType":"MKT","quantity":"1","exchange":"NSE","symbol":"NIFTY1!","instrument":"FUT","productType":"M","sort_order":"1","price":"0"}]}'
short_exit_msg = '{"secret":"C0B2u","alertType":"multi_leg_order","order_legs":[{"transactionType":"B","orderType":"MKT","quantity":"1","exchange":"NSE","symbol":"NIFTY1!","instrument":"FUT","productType":"M","sort_order":"1","price":"0"}]}'
// Submit orders based on signals
if(strategy.position_size == 0)
if long_entry
strategy.order("Long", strategy.long,alert_message=long_msg)
if short_entry
strategy.order("Short", strategy.short,alert_message=short_msg)
if(strategy.position_size > 0)
if(short_entry)
strategy.order("Short", strategy.short, qty = size, alert_message=short_msg)
else
strategy.exit("Long Exit", from_entry="Long", qty = size, stop=stop_loss_price, limit= target_price, alert_message=long_exit_msg)
if(strategy.position_size < 0)
if(long_entry)
strategy.order("Long", strategy.long, qty = size, alert_message=long_msg)
else
strategy.exit("Short Exit", from_entry="Short", qty = size, stop=stop_loss_price, limit= target_price, alert_message=short_exit_msg)