Chiến lược dự đoán hình thái


Ngày tạo: 2023-09-28 11:11:35 sửa đổi lần cuối: 2023-09-28 11:11:35
sao chép: 0 Số nhấp chuột: 785
1
tập trung vào
1617
Người theo dõi

Tổng quan

Chiến lược dự đoán hình dạng sử dụng hình dạng đồ thị để đánh giá xu hướng giá trong tương lai, được sử dụng rộng rãi trong giới giao dịch. Chiến lược này nắm bắt cơ hội đảo ngược xu hướng bằng cách nhận ra hai hình dạng đơn giản là đường nón và ngôi sao bắn.

Nguyên tắc chiến lược

Chiến lược này dựa trên các nguyên tắc sau:

  1. Sử dụng chỉ số ATR để xác định xu hướng mạnh và yếu, lọc ra thị trường chấn động. ATR chỉ được xem xét khi giá trị ATR nhỏ hơn hoặc lớn hơn ngưỡng giảm tối đa.

  2. Tính toán 33.3% đường Fibonacci rút lui của đường K hiện tại. Nếu giá trị mua bán cao hơn đường này thì được coi là đường thỏ, nếu giá trị mua bán thấp hơn đường này thì được coi là các ngôi sao bắn.

  3. Xác nhận bổ sung cho hình thức được xác định, yêu cầu hình thức được hoàn thành ((các phần thực thể cao hơn hoặc thấp hơn giá mở cửa) và là đường K chưa xác nhận.

  4. Sau khi vào, thiết lập dừng và dừng, dừng là một số lần ATR, dừng là một số lần lợi nhuận rủi ro của dừng.

Chiến lược này sử dụng chỉ số ATR và kỹ thuật Fibonacci để xác định hình dạng của các đường nón và các ngôi sao bắn, đồng thời thiết lập các chỉ số kiểm soát rủi ro, phù hợp với nguyên tắc chung của giao dịch xu hướng.

Phân tích lợi thế

Chiến lược này có những ưu điểm sau:

  1. Các nguyên tắc rất đơn giản, dễ hiểu và thực hiện.

  2. Sử dụng hình thức ngắn hạn trong ngày, không cần phải chờ đợi lâu để giữ vị trí, linh hoạt.

  3. Cài đặt tham số ATR kiểm soát rủi ro quá mức. Các tham số có thể được tối ưu hóa cho các giống khác nhau.

  4. Kết hợp với tỷ lệ lợi nhuận rủi ro để thiết lập điểm dừng lỗ hợp lý, rủi ro có thể được kiểm soát.

  5. Tín hiệu giao dịch tự động được kết nối trực tiếp với lệnh dừng lỗ, hoạt động đơn giản.

  6. Có thể áp dụng cho nhiều giống, có tính phổ biến.

Phân tích rủi ro

Chiến lược này cũng có một số rủi ro:

  1. Các giao dịch hình thức có một tỷ lệ sai lầm nhất định, không thể hoàn toàn dựa vào.

  2. Không tính phí giao dịch, không có nhiều cơ hội kiếm được lợi nhuận thực tế.

  3. Giao dịch ngắn trong ngày có thể làm tăng tần suất giao dịch và chi phí trượt.

  4. Các tham số ATR được tối ưu hóa dựa trên dữ liệu lịch sử và không thể đảm bảo rằng tham số sẽ luôn luôn được áp dụng.

  5. Tự động đặt hàng có nguy cơ phát hành thất bại, nên thiết lập cơ chế thử lại.

  6. Thiết lập dừng lỗ không đúng có thể dẫn đến quá nhiều hoặc quá ít tiền bồi thường.

Hướng tối ưu hóa

Chiến lược này có thể được tối ưu hóa theo các hướng sau:

  1. Thêm các điều kiện lọc khác, chẳng hạn như khối lượng giao dịch, tăng hiệu quả hình thức.

  2. Xem xét các thiết lập phí, tối ưu hóa điểm dừng lỗ.

  3. Tiến động tối ưu hóa tham số ATR để phù hợp với các chu kỳ khác nhau.

  4. Đánh giá các thông số cho mỗi cặp giao dịch, đặt các tham số cá nhân.

  5. Tăng cơ chế tự động thử lại, giảm rủi ro đơn lẻ.

  6. Sử dụng học máy để cải thiện độ chính xác nhận dạng hình dạng.

  7. Thêm theo dõi dừng lỗ, khóa thêm lợi nhuận.

Tóm tắt

Tóm lại, chiến lược giao dịch này tích hợp các chỉ số kỹ thuật thường dùng, các nguyên tắc đơn giản, dễ hiểu và thực hiện. Trong trường hợp tối ưu hóa tham số và kiểm soát rủi ro, có thể đạt được lợi nhuận ổn định. Tuy nhiên, thương nhân vẫn cần chú ý đến rủi ro, giữ số lượng giao dịch vừa phải và tránh quá quyết liệt.

Mã nguồn chiến lược
/*backtest
start: 2023-08-28 00:00:00
end: 2023-09-27 00:00:00
period: 2h
basePeriod: 15m
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/
// © ZenAndTheArtOfTrading / PineScriptMastery
// Last Updated: 28th April, 2021
// @version=4
strategy("Hammers & Stars Strategy [v1.0]", shorttitle="HSS[v1.0]", overlay=true)

// Get user input
atrMinFilterSize = input(title=">= ATR Filter", type=input.float, defval=0.0, minval=0.0, tooltip="Minimum size of entry candle compared to ATR", group="Strategy Settings")
atrMaxFilterSize = input(title="<= ATR Filter", type=input.float, defval=3.0, minval=0.0, tooltip="Maximum size of entry candle compared to ATR", group="Strategy Settings")
stopMultiplier   = input(title="Stop Loss ATR", type=input.float, defval=1.0, tooltip="Stop loss multiplier (x ATR)", group="Strategy Settings")
rr               = input(title="R:R", type=input.float, defval=1.0, tooltip="Risk:Reward profile", group="Strategy Settings")
fibLevel         = input(title="Fib Level", type=input.float, defval=0.333, tooltip="Used to calculate upper/lower third of candle. (For example, setting it to 0.5 will mean hammers must close >= 50% mark of the total candle size)", group="Strategy Settings")
i_startTime      = input(title="Start Date Filter", defval=timestamp("01 Jan 2000 13:30 +0000"), type=input.time, tooltip="Date & time to begin trading from", group="Strategy Settings")
i_endTime        = input(title="End Date Filter", defval=timestamp("1 Jan 2099 19:30 +0000"), type=input.time, tooltip="Date & time to stop trading", group="Strategy Settings")
oandaDemo        = input(title="Use Oanda Demo?", type=input.bool, defval=false, tooltip="If turned on then oandapractice broker prefix will be used for AutoView alerts (demo account). If turned off then live account will be used", group="AutoView Oanda Settings")
limitOrder       = input(title="Use Limit Order?", type=input.bool, defval=true, tooltip="If turned on then AutoView will use limit orders. If turned off then market orders will be used", group="AutoView Oanda Settings")
gtdOrder         = input(title="Days To Leave Limit Order", type=input.integer, minval=0, defval=2, tooltip="This is your GTD setting (good til day)", group="AutoView Oanda Settings")
accountBalance   = input(title="Account Balance", type=input.float, defval=1000.0, step=100, tooltip="Your account balance (used for calculating position size)", group="AutoView Oanda Settings")
accountCurrency  = input(title="Account Currency", type=input.string, defval="USD", options=["AUD", "CAD", "CHF", "EUR", "GBP", "JPY", "NZD", "USD"], tooltip="Your account balance currency (used for calculating position size)", group="AutoView Oanda Settings")
riskPerTrade     = input(title="Risk Per Trade %", type=input.float, defval=2.0, step=0.5, tooltip="Your risk per trade as a % of your account balance", group="AutoView Oanda Settings")

// Set up AutoView broker prefix
var broker = oandaDemo ? "oandapractice" : "oanda"

// See if this bar's time happened within date filter
dateFilter = true

// Get ATR
atr = atr(14)

// Check ATR filter
atrMinFilter = abs(high - low) >= (atrMinFilterSize * atr) or atrMinFilterSize == 0.0
atrMaxFilter = abs(high - low) <= (atrMaxFilterSize * atr) or atrMaxFilterSize == 0.0
atrFilter = atrMinFilter and atrMaxFilter

// Calculate 33.3% fibonacci level for current candle
bullFib = (low - high) * fibLevel + high
bearFib = (high - low) * fibLevel + low

// Determine which price source closes or opens highest/lowest
lowestBody = close < open ? close : open
highestBody = close > open ? close : open

// Determine if we have a valid setup
validHammer = lowestBody >= bullFib and atrFilter and close != open and not na(atr)
validStar = highestBody <= bearFib and atrFilter and close != open and not na(atr)

// Check if we have confirmation for our setup
validLong = validHammer and strategy.position_size == 0 and dateFilter and barstate.isconfirmed
validShort = validStar and strategy.position_size == 0 and dateFilter and barstate.isconfirmed

//------------- DETERMINE POSITION SIZE -------------//
// Get account inputs
var tradePositionSize = 0.0
var pair = syminfo.basecurrency + "/" + syminfo.currency

// Check if our account currency is the same as the base or quote currency (for risk $ conversion purposes)
accountSameAsCounterCurrency = accountCurrency == syminfo.currency
accountSameAsBaseCurrency = accountCurrency == syminfo.basecurrency

// Check if our account currency is neither the base or quote currency (for risk $ conversion purposes)
accountNeitherCurrency = not accountSameAsCounterCurrency and not accountSameAsBaseCurrency

// Get currency conversion rates if applicable
conversionCurrencyPair = accountSameAsCounterCurrency ? syminfo.tickerid : accountNeitherCurrency ? accountCurrency + syminfo.currency : accountCurrency + syminfo.currency
conversionCurrencyRate = security(symbol=syminfo.type == "forex" ? "BTC_USDT:swap" : "BTC_USDT:swap", resolution="D", expression=close)

// Calculate position size
getPositionSize(stopLossSizePoints) =>
    riskAmount = (accountBalance * (riskPerTrade / 100)) * (accountSameAsBaseCurrency or accountNeitherCurrency ? conversionCurrencyRate : 1.0)
    riskPerPoint = (stopLossSizePoints * syminfo.pointvalue)
    positionSize = (riskAmount / riskPerPoint) / syminfo.mintick
    round(positionSize)
    
// Custom function to convert pips into whole numbers
toWhole(number) =>
    return = atr(14) < 1.0 ? (number / syminfo.mintick) / (10 / syminfo.pointvalue) : number
    return := atr(14) >= 1.0 and atr(14) < 100.0 and syminfo.currency == "JPY" ? return * 100 : return
//------------- END POSITION SIZE CODE -------------//

// Calculate our stop distance & size for the current bar
stopSize = atr * stopMultiplier
longStopPrice = low < low[1] ? low - stopSize : low[1] - stopSize
longStopDistance = close - longStopPrice
longTargetPrice = close + (longStopDistance * rr)
shortStopPrice = high > high[1] ? high + stopSize : high[1] + stopSize
shortStopDistance = shortStopPrice - close
shortTargetPrice = close - (shortStopDistance * rr)

// Save trade stop & target & position size if a valid setup is detected
var tradeStopPrice = 0.0
var tradeTargetPrice = 0.0

// Set up our GTD (good-til-day) order info
gtdTime = time + (gtdOrder * 1440 * 60 * 1000) // 86,400,000ms per day
gtdYear = year(gtdTime)
gtdMonth = month(gtdTime)
gtdDay = dayofmonth(gtdTime)
gtdString = " dt=" + tostring(gtdYear) + "-" + tostring(gtdMonth) + "-" + tostring(gtdDay)

// Detect valid long setups & trigger alert
if validLong
    tradeStopPrice := longStopPrice
    tradeTargetPrice := longTargetPrice
    tradePositionSize := getPositionSize(toWhole(longStopDistance) * 10)
    // Trigger AutoView long alert
    alert(message="e=" + broker + " b=long q="
     + tostring(tradePositionSize) 
     + " s=" + pair
     + " t=" + (limitOrder ? "limit fp=" + tostring(close) : "market")
     + " fsl=" + tostring(tradeStopPrice)
     + " ftp=" + tostring(tradeTargetPrice)
     + (gtdOrder != 0 and limitOrder ? gtdString : ""), 
     freq=alert.freq_once_per_bar_close)
   
// Detect valid short setups & trigger alert
if validShort
    tradeStopPrice := shortStopPrice
    tradeTargetPrice := shortTargetPrice
    tradePositionSize := getPositionSize(toWhole(shortStopDistance) * 10)
    // Trigger AutoView short alert
    alert(message="e=" + broker + " b=short q="
     + tostring(tradePositionSize)
     + " s=" + pair
     + " t=" + (limitOrder ? "limit fp=" + tostring(close) : "market")
     + " fsl=" + tostring(tradeStopPrice)
     + " ftp=" + tostring(tradeTargetPrice)
     + (gtdOrder != 0 and limitOrder ? gtdString : ""),
     freq=alert.freq_once_per_bar_close)

// Enter trades whenever a valid setup is detected
strategy.entry(id="Long", long=strategy.long, when=validLong)
strategy.entry(id="Short", long=strategy.short, when=validShort)

// Exit trades whenever our stop or target is hit
strategy.exit(id="Long Exit", from_entry="Long", limit=tradeTargetPrice, stop=tradeStopPrice, when=strategy.position_size > 0)
strategy.exit(id="Short Exit", from_entry="Short", limit=tradeTargetPrice, stop=tradeStopPrice, when=strategy.position_size < 0)

// Draw trade data
plot(strategy.position_size != 0 or validLong or validShort ? tradeStopPrice : na, title="Trade Stop Price", color=color.red, style=plot.style_linebr, transp=0)
plot(strategy.position_size != 0 or validLong or validShort ? tradeTargetPrice : na, title="Trade Target Price", color=color.green, style=plot.style_linebr, transp=0)
plot(strategy.position_size != 0 or validLong or validShort ? tradePositionSize : na, color=color.purple, transp=100, title="AutoView Position Size")

// Draw price action setup arrows
plotshape(validLong ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.green, title="Bullish Setup")
plotshape(validShort ? 1 : na, style=shape.triangledown, location=location.abovebar, color=color.red, title="Bearish Setup")