Strategy · Pine Script v5 · On the chart

Kondor EMA

by arrabyte· code credited to CiclicaTrading - 2023 Strambatax (Alessandro Arrabito)

Strategy that trades crossovers of a 7-period and a 25-period EMA, filtered by a 200-period EMA: longs when the fast line crosses above and the slow line is above the trend line, shorts in the opposite case.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code188
Settings16inputs
LicenceNone statedfile: MPL-2.0
Last update3 years ago30 Jul 2023

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

188 lines of Pine Script v5 from simpleEmaStrategy.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

simpleEmaStrategy.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © CiclicaTrading - 2023 Strambatax (Alessandro Arrabito) 
// https://www.youtube.com/watch?v=g7TNcMseFYE

// ████████  ██     ██
// ██░██░░░   ██  ██
// ████████░    ██
//    ██ ██   ██  ██
// ████████  ██     ██

//@version=5 
strategy("Kondor_Ema", overlay=true, default_qty_type=strategy.percent_of_equity, initial_capital = 1000,
 default_qty_value=100,  commission_type=strategy.commission.percent, commission_value=0.061)

// Campi di input nella scheda dei settting 
int emaFastLen = input.int(7, "Ema Fast", step = 1, group = "Ma settings")
int emaSlowLen = input.int(25, "Ema Slow", step = 1, group = "Ma settings") 
int trendMaLen = input.int(200, "Trend Ma", step = 1, group = "Ma settings")

// offset del trailing stop espresso in percentuale
bool enableTrailStopOnTp = input.bool(false, "Enable Trail stop on take profit", group = "strategy settings")
float trailStopOffsetPrc = input.float(1.0, "Trail offset Prc", step=0.1, group = "strategy settings") / 100
bool enableTrailStopLossAtr = input.bool(false, "Trail stop loss by Atr", group = "strategy settings")

// risk reward 1:X quindi si imposta X cioè il valore di rendimento. 
// default 1.0 => rischio = rendimento, se imporsto 2.0 => rendimento doppio rispetto al rischio.
bool enablePartialTp = input.bool(false, "Enable partial take profit", group = "strategy settings")
float riskReward = input.float(1.5, "Risk reward", step=0.1, group = "strategy settings")
bool breakEvenEnabled = input.bool(true, "Break Even Enabled", tooltip = "if enabled move stop to breakevent if price reach partial take profit", group = "strategy settings")

// periodo atr
int atrLen = input.int(11, "atr len", group = "atr settings")

// moltiplicatore per definire il livello di stop loss
float atrMultiplier = input.float(3.0, "atr Multiplier", step=0.1, group = "atr settings")

bool atrDraw = input.bool(false, "atr band draw", group = "atr settings")

string botLongEntryCmd = input.text_area("", "wundertrading entry long command", group = "bot")
string botLongExitCmd = input.text_area("", "wundertrading exit long command", group = "bot")
string botShortEntryCmd = input.text_area("", "wundertrading entry short command", group = "bot")
string botShortExitCmd = input.text_area("", "wundertrading exit short command", group = "bot")

// Calcolo delle medie mobili esponenziali
emaFast = ta.ema(close, emaFastLen)
emaSlow = ta.ema(close, emaSlowLen)
trendMa = ta.ema(close, trendMaLen)

// Funzioni grafiche per disegnare le medie mobili
plot(emaFast, color = color.yellow, linewidth = 2)
plot(emaSlow, color = color.blue, linewidth = 2)
plot(trendMa, color = color.gray, linewidth = 2)

// Condizioni di ingresso
bool emaCrossLong = ta.crossover(emaFast, emaSlow)
bool emaCrossShort = ta.crossunder(emaFast, emaSlow)

bool entryLong = emaCrossLong and emaSlow > trendMa
bool entryShort = emaCrossShort and emaSlow < trendMa

//// Variabili che mantengono i livelli del trade in corso.
var float stopLossLevel = na
var float takeProfitLevel = na
var float partialTakeProfitLevel = na
var float entryLevel = na
var float beLevel = na


// Grafica: disegno dei livelli del trade tramite funzioni plot e fill.
entryLine = plot(entryLevel, color=color.yellow, style = plot.style_linebr)
pTpLine = plot(partialTakeProfitLevel, color=color.fuchsia, style = plot.style_linebr, linewidth = 2)
tpLine = plot(takeProfitLevel, color=color.green, style = plot.style_linebr)
slLine = plot(stopLossLevel, color=color.red, style = plot.style_linebr)

fill(entryLine, tpLine, color.new(color.green, 50))
fill(entryLine, slLine, color.new(color.red, 50))
 
float atr = ta.atr(atrLen)
float atrOffset = atr*atrMultiplier

plot(atrDraw ? close + atrOffset : na)
plot(atrDraw ? close - atrOffset : na)

getTickValue() =>
    syminfo.mintick * syminfo.pointvalue

trailStopOffset = close * trailStopOffsetPrc / getTickValue()

// Questa funzione aggiorna i livelli di uscita con trail e senza trail.
updateExits(direction) =>
    if direction == "long"    
        if enableTrailStopOnTp
            strategy.exit("long_exit_id", "long_id", stop = stopLossLevel, trail_price = takeProfitLevel, trail_offset = trailStopOffset)
        else
            strategy.exit("long_exit_id", "long_id", stop = stopLossLevel, limit = takeProfitLevel, alert_message = botLongExitCmd)
    else if direction == "short"   
        if enableTrailStopOnTp
            strategy.exit("short_exit_id", "short_id", stop = stopLossLevel, trail_price = takeProfitLevel, trail_offset = trailStopOffset)
        else
            strategy.exit("short_exit_id", "short_id", stop = stopLossLevel, limit = takeProfitLevel, alert_message = botShortExitCmd)

// blocco di apertura dei trade long e short
// se si verificano le condizioni.
if entryLong and strategy.position_size == 0
    entryLevel := close

    // stop loss proporzionale al livello di atr
    stopLossLevel := close - atrOffset
    takeProfitLevel := close + atrOffset*riskReward
    partialTakeProfitLevel := enablePartialTp ? close + atrOffset*riskReward/2 : na
    beLevel := close + atrOffset*riskReward/2

    strategy.entry("long_id", strategy.long, alert_message = botLongEntryCmd)
    if not na(partialTakeProfitLevel)
        strategy.exit("p1_long_exit_id", "long_id", stop = stopLossLevel, limit = partialTakeProfitLevel, qty_percent = 50)
    updateExits("long")
if entryShort and strategy.position_size == 0
    entryLevel := close
    stopLossLevel := close + atrOffset
    takeProfitLevel := close - atrOffset*riskReward
    partialTakeProfitLevel := enablePartialTp ? close - atrOffset*riskReward/2 : na
    beLevel := close - atrOffset*riskReward/2

    strategy.entry("short_id", strategy.short, alert_message = botShortEntryCmd)    
    if not na(partialTakeProfitLevel)
        strategy.exit("p1_short_exit_id", "short_id", stop = stopLossLevel, limit = partialTakeProfitLevel, qty_percent = 50)
    updateExits("short")

// blocco per abilitira la chiusura a breakeven
if breakEvenEnabled and strategy.position_size > 0 and high > beLevel and barstate.isconfirmed
    stopLossLevel := entryLevel
    updateExits("long")
if breakEvenEnabled and strategy.position_size < 0 and low < beLevel and barstate.isconfirmed
    stopLossLevel := entryLevel
    updateExits("short")

// trailing stop loss atr
if strategy.position_size > 0 and barstate.isconfirmed and enableTrailStopLossAtr
    //if atrOffset > stopLossLevel 
    if close - atrOffset > stopLossLevel 
        stopLossLevel := close - atrOffset
        if not na(partialTakeProfitLevel)
            strategy.exit("p1_long_exit_id", "long_id", stop = stopLossLevel, limit = partialTakeProfitLevel, qty_percent = 50)
        updateExits("long")
if strategy.position_size < 0 and barstate.isconfirmed and enableTrailStopLossAtr
    //if atrOffset < stopLossLevel 
    if close + atrOffset < stopLossLevel 
        stopLossLevel := close + atrOffset
        if not na(partialTakeProfitLevel)
            strategy.exit("p1_short_exit_id", "short_id", stop = stopLossLevel, limit = partialTakeProfitLevel, qty_percent = 50)
        updateExits("short")


// Reset delle variabili in chiusura del trade.
// Come accennato nel video, il seguente snippet di codice non gestisce il caso di un trade che 
// inizia e finisce durante la stessa candela. Per questo lascio nel commento la soluzione.
// condizioneDiUscita = strategy.position_size == 0 and strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1) == bar_index
if strategy.position_size == 0 and strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1) == bar_index
    stopLossLevel := na
    takeProfitLevel := na
    partialTakeProfitLevel := na
    entryLevel := na
    beLevel := na

var float totProfit = 0
if ta.change(strategy.closedtrades)
    tradeIndex = strategy.closedtrades -1
    tradeId = strategy.closedtrades.exit_id(tradeIndex)
    if tradeId == "long_exit_id" or tradeId == "short_exit_id"
        p2 = strategy.closedtrades.profit(tradeIndex)
        p1 = strategy.closedtrades.profit(tradeIndex - 1)
        label.new(bar_index, close, str.format("{0, number, #.##}", p1+p2), style = label.style_label_lower_left, color = p1+p2 > 0 ? color.green : color.red)
        totProfit += p1 + p2

// tabella riepilogo dati strategia
var tableInfo = table.new(position.top_right, 2,2)
tableInfo.set_bgcolor(color.white)
table.cell(tableInfo, 0, 0, "Info")
table.cell(tableInfo, 0, 1, "Profit")
table.cell(tableInfo, 1, 1, str.format("{0, number, #.##}", totProfit))

// Settings
// FTMUSDT TF 1H
// ema 7, 23, 200
// enable partial tp
// RR 1,6
// enable breakeven
// ATR len 3 mul 3.1

Overview

Stop loss uses an ATR multiple, with a risk-reward target, optional partial take profit, break-even and trailing stop settings. Position size defaults to percent of equity. Text fields allow alert commands for an external trading bot.

Details

Published by

arrabyte on GitHub

Code credit

CiclicaTrading - 2023 Strambatax (Alessandro Arrabito), as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Moving averages

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Ema Fastint7emaFastLen
Ema Slowint25emaSlowLen
Trend Maint200trendMaLen
Enable Trail stop on take profitboolfalseenableTrailStopOnTp
Trail offset Prcfloat1.0trailStopOffsetPrc
Trail stop loss by AtrboolfalseenableTrailStopLossAtr
Enable partial take profitboolfalseenablePartialTp
Risk rewardfloat1.5riskReward
Break Even EnabledbooltruebreakEvenEnabled
atr lenint11atrLen
atr Multiplierfloat3.0atrMultiplier
atr band drawboolfalseatrDraw
Show all 16 settings
SettingTypeDefaultVariable
wundertrading entry long commandtextbotLongEntryCmd
wundertrading exit long commandtextbotLongExitCmd
wundertrading entry short commandtextbotShortEntryCmd
wundertrading exit short commandtextbotShortExitCmd
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

Doge SMA

by hackingthemarkets
474 stars

Doge SMA is a long-only moving-average crossover strategy drawn on the price chart. It calculates a fast and a slow simple moving average of close and enters a long position when the fast average crosses above the slow average, but only inside a user-defined s

Strategy v4 TrendMoving averages
Updated 4 years ago · None stated GitHub repository of Doge SMA

This strategy calculates and plots a fast Exponential Moving Average (EMA) and a slow EMA directly on the main price chart. It enters long trades when the fast EMA crosses above the slow EMA and exits when the fast EMA crosses below the slow EMA. Inputs allow

Strategy v6 TrendMoving averages
Updated yesterday · AGPL-3.0 GitHub repository of Forven S01508 — Simple EMA20/50 Cross
330 stars

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

Acrypto - Weighted Strategy

by AlbertoCuadra
318 stars

This strategy plots on the price chart and opens long or short positions when a weighted score from MACD, Stochastic RSI, RSI, Supertrend and a moving-average crossover exceeds a user-set trigger. Each component has its own weight and candle delay. Entries can

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · Custom licence GitHub repository of Acrypto - Weighted Strategy
257 stars

This strategy calculates dynamic support and resistance levels using pivot highs and lows alongside a custom smoothed trend filter and a 3-period EMA. It identifies entry opportunities when price breaks out relative to the trend filter and short-term EMA cross

Strategy v5 TrendSupport & resistance Repaints
Updated 6 weeks ago · None stated GitHub repository of 30s - ES 1m Strategy Candle Bar

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers