거북이 거래 결정 시스템

저자:차오장, 날짜: 2024-02-29 14:28:25
태그:

img

전반적인 설명

거북이 거래 결정 체계 (Turtle Trading Decision System) 는 브레이크아웃 이론에 기반한 트렌드를 따르는 거래 전략이다. 잠재적인 트렌드를 식별하기 위해 특정 기간 동안 가장 높고 가장 낮은 가격의 이동 평균을 통해 거래 신호를 생성한다. 거래 신호는 가격이 지정된 기간 동안 가장 높고 가장 낮은 가격보다 높거나 낮을 때 생성된다. 이 전략은 또한 트레일링 스톱, 피라미딩 및 돈 관리 모듈을 통합하여 비교적 완전한 의사 결정 시스템을 형성한다.

전략 원칙

거북이 거래 결정 시스템의 핵심 전략 신호는 N1 기간 동안 가장 높은 가격과 N2 기간 동안 가장 낮은 가격을 비교하여 생성됩니다. 가격이 N1 기간 동안 가장 높은 가격 이상으로 넘을 때 긴 신호가 생성됩니다. 가격이 N2 기간 동안 가장 낮은 가격 이하로 넘을 때 짧은 신호가 생성됩니다. 종료 모드는 새로운 신호 생성을 제어하는 데 사용됩니다.

포지션을 열면, 가격은 트레일링 스톱 신호를 생성하기 위해 실시간으로 스톱 로스 가격과 비교됩니다. 또한, 피라미드 신호를 생성하기 위해 추가 라인과 가격을 비교하십시오. 스톱 로스 가격과 추가 라인은 ATR과 관련이 있습니다.

포지션 개설 시 매번 포지션 단위는 초기 자본의 특정 비율을 취해서 계산되는데, 이는 단일 손실이 전체 자본에 미치는 영향을 피하기 위해서입니다. 단일 손실은 특정 범위 내에서 제한됩니다.

이점 분석

거북이 거래 결정 시스템은 다음과 같은 장점을 가지고 있습니다.

  1. 잠재적인 경향을 파악: 잠재적인 경향 방향을 결정하기 위해 기간 동안 가장 높고 가장 낮은 가격과 가격을 비교함으로써 잠재적인 가격 추세를 더 일찍 파악할 수 있습니다.

  2. 리스크 관리: 단일 및 전체 손실 위험을 제어하기 위해 돈 관리 및 스톱 손실을 사용하십시오.

  3. 피라미딩 관리: 적절한 피라미딩은 트렌드로부터 추가 수익을 얻을 수 있습니다.

  4. 무결성: 돈 관리, 스톱 손실 관리 및 피라미드 관리를 결합하면 의사 결정 시스템이 더 완전합니다.

  5. 간단하고 명확합니다. 신호 생성 규칙은 간단하고 직설적이며 이해하기 쉽고 확인하기 쉽습니다.

위험 분석

거북이 거래 결정 시스템은 또한 몇 가지 위험을 가지고 있습니다.

  1. 가짜 브레이크 위험: 가격이 가장 높거나 가장 낮은 가격 이상 또는 아래에 잘못된 브레이크를 가질 수 있으며 잘못된 신호를 유발할 수 있습니다. 일부 잘못된 브레이크를 필터링하기 위해 매개 변수를 적절히 조정할 수 있습니다.

  2. 트렌드 역전 위험: 가격이 역전되면 피라미딩 후 손실이 증가 할 위험이 있습니다. 피라미딩의 수는 적절히 제한되어 적시에 손실을 중단해야합니다.

  3. 매개 변수 최적화 위험: 매개 변수 설정은 다른 시장에 따라 크게 다를 수 있습니다. 매개 변수는 위험을 줄이기 위해 각 시장에 개별적으로 최적화해야합니다.

최적화 방향

거북이 거래 결정 시스템은 다음 측면에서도 최적화 될 수 있습니다:

  1. 필터를 추가합니다. 일부 가짜 브레이크를 필터링하기 위해 가격 브레이크의 동력을 감지합니다.

  2. 스톱 로스 전략을 최적화: 스톱 로스를 합리적으로 추적하고 이익을 보호하고 불필요한 스톱 로스를 줄이는 균형을 찾는 방법.

  3. 시장별 매개 변수 최적화: 다른 품종의 특성을 위해 매개 변수 조합을 최적화합니다.

  4. 머신러닝을 추가합니다. 트렌드 방향을 판단하는 데 도움이 되는 머신러닝 알고리즘을 사용하세요.

요약

거북이 거래 결정 시스템은 특정 기간 동안 가장 높은 가격과 가장 낮은 가격과 가격을 비교하여 잠재적 인 트렌드 방향을 판단하고 위험 관리 모듈로 전체 결정 시스템을 구성합니다. 강력한 트렌드 추적 기능을 가지고 있으며 잘못된 브레이크와 매개 변수 최적화의 위험도 있습니다. 이 전략은 양적 거래의 기본 모델로 사용될 수 있으며 이에 따라 적절한 의사 결정 시스템을 개발하고 최적화 할 수 있습니다.


/*backtest
start: 2024-01-29 00:00:00
end: 2024-02-28 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © 李和邪 
// 本脚本所有内容只适用于交流学习,不构成投资建议,所有后果自行承担。
//@version=5
strategy(title='Turtle Trading Strategy@lihexie',
   shorttitle='OKX-海龟交易系统@李和邪',
   overlay=true,
   pyramiding=4,
   initial_capital = 1000,
   default_qty_type = strategy.percent_of_equity,
   default_qty_value=100,
   slippage = 0,
   commission_type = strategy.commission.percent,
   commission_value = 0.05)

// 输入参数
from_date = input(timestamp("2013-01-01T00:00:00+08:00"), "From Date/开始日期")
end_date = input(timestamp("2024-08-01T00:00:00+08:00"), "To Date/结束日期")
valid_date() => true
current_mode = input.string("Mode 1", "Enter Mode/进场系统",['Mode 1','Mode 2'])
// mode 1
entry_length = input.int(20, 'Entry Length/系统1进场长度', minval=1)  // 进场长度
exit_length = input.int(10, 'Exit Length/系统2出场长度', minval=1)  // 出场长度
// mode 2
entry_length_mode2 = input.int(55, 'Mode2 Entry Length/系统2进场长度', minval=1)  // 进场长度
exit_length_mode2 = input.int(20, 'Mode2 Exit Length/系统2出场长度', minval=1) 
atr_period = input.int(14, "ATR Period/计算ATR的周期", minval=1)  // ATR周期
risk_per_trade = input.float(0.02, "Risk Per Trade/每笔交易的风险,0.02就是2%", minval=0.001, maxval=1)  // 每笔交易的风险
initial_stop_atr_multiple = input.float(2, "Initial Stop ATR Multiple/止损使用的ATR倍数", minval=0.1, maxval=10)  // 初始止损ATR倍数
pyramid_atr_multiple = input.float(0.5, "Pyramid ATR Multiple/加仓使用的ATR倍数", minval=0.1, maxval=10)  // 加仓ATR倍数
max_units = input.int(4, "Max Units/最大头寸单位数", minval=1, maxval=10)  // 最大头寸单位数

highlighting = input(title='Highlighter On/Off ?/是否高亮显示', defval=true)  // 是否高亮显示


// 初始化变量
var int units = 0
var float trailing_stop_long = na
var float trailing_stop_short = na
var float real_entry_price_long = na
var float real_entry_price_short = na
var float add_unit_price_long = na
var float add_unit_price_short = na
var bool last_trade_win = false
// 计算ATR
atr = ta.atr(atr_period)

// 计算单位大小
unit_size = (strategy.equity * risk_per_trade) / (initial_stop_atr_multiple * atr)

// 切换模式
mode_signal = current_mode == "Mode 1" ? (last_trade_win==false?true:false) : true

float entry_price_long = na
float entry_price_short = na
float exit_price_long = na
float exit_price_short = na
// 计算进场和出场价格
if current_mode == "Mode 1"
    entry_price_long := ta.highest(entry_length)
    entry_price_short := ta.lowest(entry_length)
    exit_price_long := ta.lowest(exit_length)
    exit_price_short := ta.highest(exit_length)
else
    entry_price_long := ta.highest(entry_length_mode2)
    entry_price_short := ta.lowest(entry_length_mode2)
    exit_price_long := ta.lowest(exit_length_mode2)
    exit_price_short := ta.highest(exit_length_mode2)

// 计算止损价格
stop_price_long = entry_price_long - (initial_stop_atr_multiple * atr)
stop_price_short = entry_price_short + (initial_stop_atr_multiple * atr)

// 交易逻辑
// 生成买入和卖出信号
long_signal = ta.crossover(close, entry_price_long[1]) and strategy.position_size==0 and valid_date()
short_signal = ta.crossunder(close, entry_price_short[1]) and strategy.position_size==0 and valid_date()
// 生成出场信号
exit_long_signal = ta.crossunder(close, exit_price_long[1]) and strategy.position_size > 0 and valid_date()
exit_short_signal = ta.crossover(close, exit_price_short[1]) and strategy.position_size < 0 and valid_date()

if long_signal 
    if mode_signal
        strategy.entry("Long", strategy.long, qty=unit_size, stop=stop_price_long)
        units := 1
        trailing_stop_long := stop_price_long
        real_entry_price_long := close
        add_unit_price_long := real_entry_price_long+pyramid_atr_multiple*atr
    else
        last_trade_win:=false
if short_signal 
    if mode_signal
        strategy.entry("Short", strategy.short, qty=unit_size, stop=stop_price_short)
        units := 1
        trailing_stop_short := stop_price_short
        real_entry_price_short := close
        add_unit_price_short := real_entry_price_short-pyramid_atr_multiple*atr
    else
        last_trade_win:=false
// 出场逻辑
if exit_long_signal
    last_trade_win := strategy.position_avg_price<close?true:false
    strategy.close_all("SL")
    units := 0
    real_entry_price_long := na
    add_unit_price_long := na
    trailing_stop_long := na
if exit_short_signal
    last_trade_win := strategy.position_avg_price>close?true:false
    strategy.close_all("SS")
    units := 0
    real_entry_price_short := na
    add_unit_price_short := na
    trailing_stop_short := na

// 生成加仓信号
add_unit_signal = (close > add_unit_price_long or close < add_unit_price_short) and units[1] < max_units and valid_date()
// 加仓逻辑
if add_unit_signal
    if strategy.position_size > 0
        strategy.entry("AL", strategy.long, qty=unit_size)
        real_entry_price_long := close
        add_unit_price_long := real_entry_price_long+pyramid_atr_multiple*atr
        trailing_stop_long := real_entry_price_long - (initial_stop_atr_multiple * atr)
    if strategy.position_size < 0
        strategy.entry("AS", strategy.short, qty=unit_size)
        real_entry_price_short := close
        add_unit_price_short := real_entry_price_short-pyramid_atr_multiple*atr
        trailing_stop_short := real_entry_price_short + (initial_stop_atr_multiple * atr)
    units := units + 1

// 移动止损逻辑
trailing_stop_long_signal = ta.crossunder(close, trailing_stop_long) and strategy.position_size > 0 and valid_date()
trailing_stop_short_signal = ta.crossover(close, trailing_stop_short) and strategy.position_size < 0 and valid_date()

if trailing_stop_long_signal
    last_trade_win := strategy.position_avg_price<close?true:false
    strategy.close_all("TSL")
    units := 0
    real_entry_price_long := na
    add_unit_price_long := na
    trailing_stop_long := na
if trailing_stop_short_signal
    last_trade_win := strategy.position_avg_price>close?true:false
    strategy.close_all("TSS")
    units := 0
    real_entry_price_short := na
    add_unit_price_short := na
    trailing_stop_short := na

// 美化图表
plot_entry_lowest = plot(entry_price_short, 'Lower', color=color.new(#0094FF, 0))  // 绘制进场最低线
plot_entry_highest = plot(entry_price_long, 'Upper', color=color.new(#0094FF, 0))  // 绘制进场最高线
entry_line = ta.barssince(short_signal) <= ta.barssince(long_signal) ? entry_price_short : entry_price_long  // 进场线
exit_line = ta.barssince(short_signal) <= ta.barssince(long_signal) ? exit_price_short : exit_price_long  // 出场线
plot(entry_line, title='Trend Line', color=color.new(#ff52f1, 0), linewidth=2)  // 绘制趋势线
plot_exit = plot(exit_line, title='Exit Line', color=color.new(color.blue, 0), linewidth=1, style=plot.style_circles)  // 绘制出场线

entry_long_color = highlighting and strategy.position_size>0 ? color.new(color.green, transp = 88) : na
entry_short_color = highlighting and strategy.position_size<0 ? color.new(color.red, transp = 88) : na
fill(plot_entry_highest, plot_exit, color=entry_long_color, title='Background') // 高亮多头趋势
fill(plot_entry_lowest, plot_exit, color=entry_short_color, title='Background') // 高亮空头趋势

더 많은