Stratégie d'arrêt coulissant


Date de création: 2023-10-07 16:11:45 Dernière modification: 2023-10-07 16:11:45
Copier: 0 Nombre de clics: 701
1
Suivre
1617
Abonnés

Aperçu

La stratégie utilise le filtre de Kalman pour suivre les prix et utilise la ligne de stop pour ajuster dynamiquement le point de stop pour réaliser un stop glissant.

Le principe

La stratégie utilise le filtre de Kármán pour suivre les prix en temps réel. Le filtre de Kármán comporte deux équations:

L’équation de prédiction:

smooth = kf[1] + dk * sqrt(gain / 10000 * 2)

Mise à jour de la formule:

kf = smooth + velo

Dans ce cas, dk est l’erreur de prévision, gain est le gain de Kalman, et la décision de suivre la sensibilité.

De plus, la stratégie utilise une ligne de stop-loss coulissante pour verrouiller les bénéfices. La distance de stop-loss initiale est une valeur de paramétrage en pourcentage de stop-loss, comme 2%.

Si le prix augmente, le stop-loss se rapproche progressivement de la ligne de Kalman, avec une longueur de descente de 0,5%. Si le prix baisse, le stop-loss est réouvert et la distance de stop-loss initiale est définie.

Je ne suis pas d’accord avec toi.

De cette façon, la stratégie permet de verrouiller progressivement les bénéfices en fonction des tendances, avec une meilleure gestion des risques.

Les avantages

  1. Les prix sont suivis en temps réel par le filtre KALMAN, qui réagit rapidement.

  2. La gestion des risques est plus efficace grâce à l’utilisation d’une ligne de stop-loss coulissante. La distance de stop-loss est personnalisable.

  3. Vous pouvez choisir de faire plus de temps libre ou seulement plus de temps libre.

  4. Il est possible d’arrêter activement ou de conserver la perte en fonction de la tendance.

  5. Le freinage peut être réglé de manière flexible.

Les risques

  1. Une mauvaise configuration des paramètres du filtre de Kalman peut entraîner une instabilité du suivi.

  2. Le point de glissement peut entraîner le déclenchement du point d’arrêt. La distance d’arrêt peut être allégée de manière appropriée.

  3. Il est préférable de suivre la tendance plutôt que d’adopter une stratégie de stop loss glissante.

  4. Les points d’arrêt du marché oscillant peuvent être déclenchés fréquemment. La distance d’arrêt peut être assouplie de manière appropriée ou l’arrêt de glissement peut ne pas être utilisé.

Optimisation

  1. Il est possible d’introduire plus d’indicateurs pour déterminer la direction de la tendance et optimiser le moment de la prise de position.

  2. La longueur de la ligne de stop loss peut être ajustée en fonction des fluctuations du marché.

  3. Les meilleurs paramètres de résistance à la perte peuvent être combinés à la formation de techniques d’apprentissage automatique.

  4. Il est possible de combiner plus d’indicateurs de risque et de gérer la position de manière dynamique.

Résumer

La stratégie de stop-loss en glissement est une stratégie fiable et facile à optimiser qui utilise le filtre de Kalman pour suivre les variations de prix et utilise la ligne de stop-loss en glissement pour bloquer les bénéfices, tout en garantissant la rentabilité. Elle peut être combinée avec des techniques de jugement de tendance et de gestion de position dynamique pour obtenir de meilleurs résultats stratégiques.

Code source de la stratégie
/*backtest
start: 2023-09-06 00:00:00
end: 2023-10-06 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/
// © BigCoinHunter

//@version=5
// strategy(title='Loft Strategy V1', overlay=true, 
//      pyramiding=0, default_qty_type=strategy.fixed, 
//      default_qty_value=100, initial_capital=100000, 
//      currency=currency.USD, commission_value=0.05, 
//      commission_type=strategy.commission.percent, 
//      process_orders_on_close=true)

//-------------- fetch user inputs ------------------
gain = input.float(title="Kalman Gain:", defval=1.0, minval=1.0, maxval=5000.0, step=100.0)
src = input(defval=close, title='Source:')

stopPercentMax = input.float(title='Beginning Approach(%):', defval=2.0, minval=0.1, maxval=30.0, step=0.1)
stopPercentMin = input.float(title='Final Approach(%):    ', defval=0.5, minval=0.1, maxval=30.0, step=0.1)
downStep = input.float(title='Approach Decrease Step:', defval=0.005, minval=0.0, maxval = 5, step=0.005)

tp = input.float(title="Take Profit:", defval=1.5, minval=0.0, maxval=100.0, step=0.1) * 0.01
sl = input.float(title="Stop Loss:  ", defval=0.0, minval=0.0, maxval=100.0, step=0.1) * 0.01

longEntry = input.bool(defval=true, title= 'Long Entry', inline="11")
shortEntry = input.bool(defval=true, title='Short Entry', inline="11")

//---------- backtest range setup ------------
fromDay   = input.int(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input.int(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromYear  = input.int(defval = 2021, title = "From Year", minval = 2010)
toDay     = input.int(defval = 30, title = "To Day", minval = 1, maxval = 31)
toMonth   = input.int(defval = 12, title = "To Month", minval = 1, maxval = 12)
toYear    = input.int(defval = 2022, title = "To Year", minval = 2010)


//------------ time interval setup -----------
start     = timestamp(fromYear, fromMonth, fromDay, 00, 00)  // backtest start window
finish    = timestamp(toYear, toMonth, toDay, 23, 59)        // backtest finish window
window()  => true // create function "within window of time"

//------- define the global variables ------
enterLongComment = "ENTER LONG"
exitLongComment = "EXIT LONG"

enterShortComment = "ENTER SHORT"
exitShortComment = "EXIT SHORT"

longTPSL = "Long TP/SL"
longTP = "Long TP"
longSL = "Long SL"
shortTPSL = "Short TP/SL"
shortTP = "Short TP"
shortSL = "Short SL"

var bool long = true
var bool stoppedOutLong = false
var bool stoppedOutShort = false
var float kf = 0.0
var float velo = 0.0

//------ kalman filter calculation --------
dk = src - nz(kf[1], src)
smooth = nz(kf[1], src) + dk * math.sqrt(gain / 10000 * 2)
velo := nz(velo[1], 0) + gain / 10000 * dk
kf := smooth + velo

//--------- calculate the loft stopLoss line ---------
var stopPercent = stopPercentMax
var stopLoss = kf - kf * (stopPercent /100)

if long == true
    stopLoss := kf - (kf * (stopPercent / 100))
    
    if long[1] == true and stopLoss <= stopLoss[1]
        stopLoss := stopLoss[1]
    else if (long[1] == true)
        stopPercent := stopPercent - downStep
        if(stopPercent < stopPercentMin)
            stopPercent := stopPercentMin
    
    if(kf < stopLoss)
        long := false
        stopPercent := stopPercentMax
        stopLoss := kf + (kf * (stopPercent / 100))
        
else
    stopLoss := kf + (kf * (stopPercent / 100))
    
    if long[1] == false and stopLoss >= stopLoss[1]
        stopLoss := stopLoss[1]
    else if(long[1] == false)
        stopPercent := stopPercent - downStep
        if(stopPercent < stopPercentMin)
            stopPercent := stopPercentMin
            
    if(kf > stopLoss)
        long := true
        stopPercent := stopPercentMax
        stopLoss := kf - (kf * (stopPercent / 100))
        
//--------- calculate the input/output points -----------
longProfitPrice  = strategy.position_avg_price * (1 + tp)     // tp -> take profit percentage
longStopPrice = strategy.position_avg_price * (1 - sl)        // sl -> stop loss percentage

shortProfitPrice  = strategy.position_avg_price * (1 - tp)
shortStopPrice = strategy.position_avg_price * (1 + sl)

//------------------- determine buy and sell points ---------------------
buySignall = window() and long  and (not stoppedOutLong)
sellSignall = window() and (not long)  and (not stoppedOutShort)

//---------- execute the strategy -----------------
if(longEntry and shortEntry)
    if long 
        strategy.entry("LONG", strategy.long, when = buySignall, comment = enterLongComment)
        stoppedOutLong := true
        stoppedOutShort := false
    else 
        strategy.entry("SHORT", strategy.short, when = sellSignall, comment = enterShortComment)
        stoppedOutLong  := false
        stoppedOutShort := true

else if(longEntry)
    strategy.entry("LONG", strategy.long,  when = buySignall, comment = enterLongComment)
    strategy.close("LONG", when = sellSignall, comment = exitLongComment)
    if long 
        stoppedOutLong := true
    else
        stoppedOutLong  := false

else if(shortEntry)
    strategy.entry("SHORT", strategy.short, when = sellSignall, comment = enterShortComment)
    strategy.close("SHORT", when = buySignall, comment = exitShortComment)
    if not long
        stoppedOutShort := true
    else
        stoppedOutShort := false
    

//----------------- take profit and stop loss -----------------
if(tp>0.0 and sl>0.0)
    if ( strategy.position_size > 0 )
        strategy.exit(id="LONG", limit=longProfitPrice, stop=longStopPrice, comment = longTPSL)

    else if ( strategy.position_size < 0 )
        strategy.exit(id="SHORT", limit=shortProfitPrice, stop=shortStopPrice, comment = shortTPSL)

else if(tp>0.0)
    if ( strategy.position_size > 0 )
        strategy.exit(id="LONG", limit=longProfitPrice, comment = longTP)

    else if ( strategy.position_size < 0 )
        strategy.exit(id="SHORT", limit=shortProfitPrice, comment = shortTP)
        
else if(sl>0.0)
    if ( strategy.position_size > 0 )
        strategy.exit(id="LONG",  stop=longStopPrice, comment = longSL)

    else if ( strategy.position_size < 0 )
        strategy.exit(id="SHORT",  stop=shortStopPrice, comment = shortSL)
        
//------------- plot charts ---------------------
lineColor1 = long ? color.green : color.red
lineColor2 = long ? color.aqua : color.fuchsia

kalmanLine = plot(kf, color=lineColor1, linewidth=3, title = "Kalman Filter")
stopLine = plot(stopLoss, color=lineColor2, linewidth=2, title = "Stop Loss Line")