strategy enter on auto Fibonacci levels when closing candle above line auto fibonacci percent 0.236 - pine-script-v5

//#version=5
//strategy enter
List item
targetlong = close * 0.2
targetshort = close * 0.2
longEntryPrice = ta.cross(close,lineId5) and close > targetlong
shortEntryPrice =ta.cross(close,lineId5) and close > targetshort
//Entry Orders auto fibonacci
if longEntryPrice
strategy.entry("Buy", strategy.long,comment = "buy")
if shortEntryPrice
strategy.entry("Sell", strategy.short,comment = "sell")

Related

Pine Script V5 - Not getting expected breakout entry price and entry in expected bar

I have a long entry buy condition where
Candle time frame is 15 minutes
Alert candle high is below lower band of bollinger bands.
entry when next candle crossover the alert candle high
This script gives entry oh high breakout + 0.01 but it does not give entry in the exact breakout candle and gives entry when price comes next time on expected entry price i.e. alert candle high + 0.01.
Requesting solution to get entry in breakout candle itself and at expected breakout price.
//#version=5
strategy("Bands Reversion", overlay=true, calc_on_every_tick=true)
//// Indicator Bollinger Bands
source = close
length = input.int(20, minval=1)
mult = input.float(1.5, minval=0.001, maxval=50)
direction = input.int(0, title = "Strategy Direction", minval=-1, maxval=1)
strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long))
basis = ta.sma(source, length)
dev = mult * ta.stdev(source, length)
upper = basis + dev
lower = basis - dev
plot(basis, color = color.red)
plot(upper)
plot(lower)
/// Trade entry time and squareoff time
TradeTime = input(title="Trade Timings",defval="0930-1130")
SqoffTime = input(title="Squareoff Timings",defval="1530-1545")
Barsinsession(TradeTime) => time(timeframe.period,TradeTime) != 0
Insession = Barsinsession(TradeTime) ? 1 : 0
endofsession = Insession == 0 and Insession[1] == 1
Sqsession = Barsinsession(SqoffTime) ? 1 : 0
SqTime = Sqsession == 1 and Sqsession[1] == 0
//// Input control and conditions
buy_condition = high[1] < lower[1] and ta.crossover(high, high[1]) and Insession
short_condition = low[1] > upper[1] and ta.crossunder(low, low[1]) and Insession
buy_alert_high = ta.valuewhen(buy_condition, high[1],0)
buy_alert_low = ta.valuewhen(buy_condition, low[1],0)
short_alert_low = ta.valuewhen(short_condition, low[1],0)
short_alert_high = ta.valuewhen(short_condition, high[1],0)
buy_alert_high1 = ta.valuewhen(buy_condition, high,0)
plot(buy_alert_high, style = plot.style_circles)
plot(buy_alert_low, style = plot.style_circles, offset = -2)
plot(short_alert_low, style = plot.style_circles)
plot(short_alert_high, style = plot.style_circles)
sell = ta.crossunder(close, low) or SqTime //// or SqTime if for intraday exit
cover = ta.crossover(close,high) or SqTime //// or SqTime if for intraday exit
plotshape(buy_condition, style = shape.triangleup, location = location.belowbar, color = color.green, text = "BUY")
plotshape(short_condition, style = shape.triangledown, location = location.abovebar, color = color.red, text = "SHORT")
long_price = ta.valuewhen(buy_condition, (buy_alert_high + 0.01),0 )
longstop = buy_alert_low - 0.01
longtgt = basis
short_price = ta.valuewhen(short_condition,short_alert_low - 0.01,0) ////short_alert_low - (0.01 * 100 * syminfo.mintick) //// ta.valuewhen(short_condition,short_alert_low - 0.01,0)
shortstop = short_alert_high + 0.01
shorttgt = basis
strategy.entry("long",direction = strategy.long, when = buy_condition, limit = long_price, comment ="BUY")
strategy.close("long", when = sell, comment = "SELL")
strategy.exit("long", from_entry = "long", stop = longstop, limit = longtgt, comment = "TG/SL_EXIT")
strategy.entry("short",direction = strategy.short, when = short_condition,limit = short_price, comment ="SHORT")
strategy.close("short", when = cover, comment = "COVER")
strategy.exit("short", from_entry = "short", stop = shortstop, limit = shorttgt, comment = "TG/SL_EXIT")
plot(strategy.position_size > 0 ? longstop : na, style = plot.style_linebr, color = color.red)
plot(strategy.position_size > 0 ? longtgt : na, style = plot.style_linebr, color = color.green)
plot(strategy.position_size < 0 ? shortstop : na, style = plot.style_linebr, color = color.red)
plot(strategy.position_size < 0 ? shorttgt : na, style = plot.style_linebr, color = color.green)

Keeping orders from closing if conditions are met & multiple orders

First time coding - trying to set up a bot that creates multiple buy orders every time the buying signal is met and closed once the short signal is triggered - and vice versa. It seems to be working in TradingView when I add the strategy to the chart however when I connect it to 3 commas it only takes in one buy order (paper trading account) - and it closes it specifically when the condition to keep the position from closing is triggered.
I think I've set up the strategy correctly to take up to six positions with pyramiding.
strategy("DEMA CROSS STRATEGY", shorttitle = "DEMAC-S", overlay = true, initial_capital = 4000, default_qty_type = strategy.percent_of_equity, default_qty_value = 20, commission_type = strategy.commission.percent, commission_value = 0.03, pyramiding = 6)
The conditions to keep a position from closing if longAction or shortAction are true, then keep the opened positions from closing, otherwise close all positions and open a long/short.
positionState = volume < valueThreshold and ADXsignal < adxThreshold
//logic
longCondition = ta.crossover(DEMA1, DEMA2) and supertrend_X_min < close and mfi+rsi/1.8 > 40 and close > WMA
shortCondition = ta.crossunder(DEMA1, DEMA2) and supertrend_X_min > close and mfi+rsi/1.8 < 60 and close < WMA and atr < .05
longAction = (longCondition and positionState)
shortAction = (shortCondition and positionState)
if (shortAction or longAction)
false
else
if (longCondition)
strategy.entry("Enter Long", strategy.long)
strategy.exit("Exit Short", stop=na)
if (shortCondition)
strategy.entry("Enter Short", strategy.short)
strategy.exit("Exit Long", stop=na)
//
//Buy and sell alerts
buyAlert = XXXXXXXXXXXXXXXXXXXXXXXXXXX
exitAlert = XXXXXXXXXXXXXXXXXXXXXXXXXXXX
if longAction ? na : longCondition
alert(buyAlert, alert.freq_once_per_bar)
if shortAction ? na : shortCondition
alert(exitAlert, alert.freq_once_per_bar)
I've tried multiple different if then statements but honestly I'm not sure if I'm just doing it plain wrong at this stage.
Like I've stated, the code works in TradingView - not in 3Commas

Strategy ATR TP/SL target doesn't stay 'locked' to my entry readings

I want a strategy to Take Profit/Stop Loss to be based on the ATR (plus multiplier). However, I want it to be whatever the readings were at the point of entry, not simply the last candle (which is what it seems to be doing). Weird thing is that I have other strategies that use this approach, and they seem fine, so I'm really stumped by what I'm doing wrong.
Any help would be much appreciated!
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dave-browning
//#version=5
strategy("Dead-Cat Bounce", overlay = true, initial_capital = 1000, default_qty_value = 100, default_qty_type = strategy.percent_of_equity, currency = currency.GBP, commission_value = 0.05, use_bar_magnifier = true)
trendEMAlength = input.int(130, "Trend EMA Length")
fastSMALength = input.int(14, "Fast SMA Length")
tpATRmultiplyer = input.float(6.2, "Short TP ATR Multiplier")
slATRmultiplier = input.float(4, "Short SL ATR Multiplier")
//Trade Conditions
shortCondition = close > ta.sma(close, fastSMALength) and close < ta.ema(close, length=trendEMAlength)
notInTrade = strategy.position_size <= 0
atr = ta.atr(14)
ema=ta.ema(close, trendEMAlength)
plot(ta.sma(close,length=fastSMALength), color=color.blue, linewidth = 2)
plot(ta.ema(close, length=trendEMAlength), color=color.yellow, linewidth = 4)
plot(low - (atr * tpATRmultiplyer), color=color.green)
plot(high + (atr * slATRmultiplier), color=color.red)
if shortCondition and notInTrade
stopLoss = (high + (atr * slATRmultiplier))
takeProfit = (low - (atr * tpATRmultiplyer))
strategy.entry("Short", strategy.short)
strategy.exit("Short Exit", "Short", limit=takeProfit, stop=stopLoss)

TRADE open and close in the same time

in the following strategy all time (trades) open and close in the same time, so I pay only fees.
I have written to tradingview assistance, they have said me (and send) to put OPEN LONG and CLOSE LONG (the first 2 lines in strategy).
But I still have the same problem, I don't know why.
All test are ok, I think that problem is with TRAIDINGVIEW HUB, but I am not scure.
Thanks for your attention and time
strategy V5
Open Long:
{"pair":"BTCUSDT","unitsPercent":"50","unitsType":"percentWallet","exchange":"Bybit","apiKey":"TradingView BYBIT ACC AFF","token":"7dfa66d6-5b94-4047-a11c-e8bdd0f1c0f4","isBuy":true,"isMarket":false,"leverage":"5","marginType":"ISOLATED","closeCurrentPosition":true,"delay":"10"}
Close Long:
{"pair":"BTCUSDT","unitsPercent":"50","exchange":"Bybit","apiKey":"TradingView BYBIT ACC AFF","token":"7dfa66d6-5b94-4047-a11c-e8bdd0f1c0f4","isClose":true,"delay":"10"}
strategy(title='Take profit (% of instrument price)', overlay=true, pyramiding=1)
// STEP 1:
// Make inputs that set the take profit % (optional)
FastPeriod = input.int(title='Fast MA Period', defval=18, minval=1, group='Moving Average')
SlowPeriod = input.int(title='Slow MA Period', defval=20, minval=1, group='Moving Average')
TPPerc = input.float(title='Long Take Profit (%)', minval=0.0, step=0.5, defval=0.9, group='TP & SL')
SLPerc = input.float(title='Long Stop Loss (%)', minval=0.0, step=0.1, defval=4, group='TP & SL')
TP_Ratio = input.float(title='Sell Postion Size % # TP', defval=100, step=1, group='TP & SL', tooltip='Example: 100 closing 100% of the position once TP is reached') / 100
// Calculate moving averages
fastSMA = ta.sma(close, FastPeriod)
slowSMA = ta.sma(close, SlowPeriod)
// Calculate trading conditions
enterLong = ta.crossover(fastSMA, slowSMA)
// Plot moving averages
plot(series=fastSMA, color=color.new(color.green, 0), title='Fase MA')
plot(series=slowSMA, color=color.new(color.red, 0), title='Slow MA')
// STEP 2:
// Figure out take profit price
percentAsPoints(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100.0 * strategy.position_avg_price / syminfo.mintick) : float(na)
percentAsPrice(pcnt) =>
strategy.position_size != 0 ? (pcnt / 100.0 + 2.0) * strategy.position_avg_price : float(na)
current_position_size = math.abs(strategy.position_size)
initial_position_size = math.abs(ta.valuewhen(strategy.position_size[1] == 0.0, strategy.position_size, 0))
TP = strategy.position_avg_price + percentAsPoints(TPPerc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
SL = strategy.position_avg_price - percentAsPoints(SLPerc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
// Submit entry orders
if enterLong
strategy.entry(id='Long', direction=strategy.long)
// STEP 3:
// Submit exit orders based on take profit price
if strategy.position_size > 0
strategy.exit('TP', from_entry='Long', qty=initial_position_size * TP_Ratio, limit=TP, stop=SL)
// Plot take profit values for confirmation
plot(series=strategy.position_size > 0 ? TP : na, color=color.new(color.green, 0), style=plot.style_circles, linewidth=1, title='Take Profit 1')
plot(series=strategy.position_size > 0 ? SL : na, color=color.new(color.red, 0), style=plot.style_circles, linewidth=1, title='Stop Loss')

How to find data of wma at the open position?

I have this plot:
WMA_point = wma(close, 9)
plot(WMA_point, title='WMA', color=#000000)
It makes a line on the chart. When the price goes up, the line moves up, and vice versa, when the price goes down, it moves down.
I know that it depends on the "close" data.
I would like to find the price data of this wma when (close == open)
EDIT:
I mean: I want to get the first data of the close line wma(close, 9), when the new candle appears, when the (close == open) . I dont need the data of the open line wma(open, 9)
You can either use WMA_point[1], which is generally where the price value of the current bar will open at. If you want to take into consideration gapping, you'll need to calculate the wma using n-1 historical close values and with the nth value the current bar's open.
//#version=5
indicator("wma open", overlay = true)
len = input.int(10)
float wtd_close_sum = 0.0
int denom = 0
for i = 1 to len - 1
wt = len - i
wtd_close_sum += close[i] * wt
denom += wt
wtd_close_sum += open * len
denom += len
wma_open = wtd_close_sum / denom
plot(wma_open)
as a function :
f_wma_open(_open, _close, _len) =>
float _wtd_close_sum = 0.0
int _denom = 0
for i = 1 to _len - 1
_wt = _len - i
_wtd_close_sum += _close[i] * _wt
_denom += _wt
_wtd_close_sum += _open * _len
_denom += _len
_wma_open = _wtd_close_sum / _denom
_wma_open
Try using open as your source:
WMA_point = wma(open, 9)
plot(WMA_point, title='WMA', color=#000000)
Cheers, and best of luck with your trading and coding
So, you need to store the price in a var when your condition is true.
var float p = na
WMA_point = wma(close, 9)
if (open == close)
p := WMA_point // This will have the wma value of the last time open == close
plot(WMA_point, title='WMA', color=#000000)