pinescript newbie: problem to implement RR as TP! can you check my script? :) - pine-script-v5

var float loLows = na
is_new_position = (strategy.position_size[1] != strategy.position_size) // This will only be true on the bar of the entry
loLows := is_new_position // Only update the value if it is a new position. Keep the old value otherwise
TPL=(strategy.position_avg_price/RR)-(loLows/RR)+strategy.position_avg_price
TPS=(strategy.position_avg_price/RR)-(hiHighs/RR)-strategy.position_avg_price
if inDateRange and (close > (ema200) and close > (ema992) and ta.crossover(ema13,ema62) and ta.crossover(ema21,ema62))
strategy.entry("entry long", strategy.long)
strategy.exit("long exit", profit=TPL, stop=loLows)
if inDateRange and(close < (ema200) and close < (ema992) and ta.crossunder(ema13,ema62) and ta.crossunder(ema21,ema62))
strategy.entry("entry short", strategy.short)
strategy.exit("short exit", profit=TPS , stop=hiHighs)

Related

Pine Script 5 - Unwanted alert messages

I receive unwanted alert messages. I would like to have only 1 "Go Long" alert when going long and then no other "Go Long" alerts until after the first "Go Short" alert. I'm having trouble getting this right.
//#version=5
strategy("Single Alert Strategy", overlay=true)
// Create flags to avoid multiple Long signals when already in Long and multiple Short signals when already in Short
isLong = false // We initialize a value and give it false (we are not in a Long position)
isLong := nz(isLong[1]) // We check the previous value and assign the previous value to this variable (when no previous value exist it will become false)
isShort = false // We initialize a value and give it false (we are not in a Short position)
isShort := nz(isShort[1]) // We check the previous value and assign the previous value to this variable (when no previous value exist it will become false)
// Long Short conditions
tot_rsi = ta.rsi(close, 14)
bullLevel = 30
bearLevel = 70
longCondition = ta.crossover(tot_rsi, bullLevel) and not isLong // Go Long only if we are not already Long
shortCondition = ta.crossunder(tot_rsi, bearLevel) and not isShort // Go Short only if we are not already Short
// Change the flags to avoid duplicate signals
if (longCondition)
isLong := true
isShort := false
if (shortCondition)
isLong := false
isShort := true
if longCondition
strategy.entry('Long', strategy.long, alert_message = "GoLong")
if shortCondition
strategy.entry('Short', strategy.short, alert_message = "GoShort")
// Plot the signals and compare them with the Alerts log
plotshape(series=longCondition, title="Long", text="Long", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
plotshape(series=shortCondition, title="Short", text="Short", style=shape.triangledown, location=location.belowbar, color=color.red, size=size.small)
I followed the instructions in the answer provided here. While the signal indicators plot correctly (no additional signals), I do get an alert message when there was no signal plotted. This strategy is newly created with a new alert and is only added to 1 chart. The alert was created at 06:58, there were signals plotted before the alert was created but it triggered at 07:05 even though there was no signal plotted.
RSI level at 07:05 was 48.20
Any ideas what may have caused this alert to trigger and how to prevent additional alerts like these?
Link to screenshot
Edit: I'm testing an alternative approach. The unwanted alerts do not come frequently so I may have to run it for some time. If anyone knows of a different work around then I'm happy to give that a try.
//#version=5
strategy("Single Alert Strategy", overlay=true, calc_on_every_tick = true)
noOrder = strategy.closedtrades == 0 // There is no previous order
openLong = strategy.position_size > 0 // We are going Long
openShort = strategy.position_size < 0 // We are going Short
// Long Short conditions
tot_rsi = ta.rsi(close, 14)
bullLevel = 30
bearLevel = 70
longCondition = ta.crossover(tot_rsi, bullLevel) and (openShort[1] or noOrder) // Go Long only if the previous order was Short
shortCondition = ta.crossunder(tot_rsi, bearLevel) and (openLong[1] or noOrder) // Go Short only if the previous order was Long
if longCondition
strategy.entry('Long', strategy.long, alert_message = "GoLong")
if shortCondition
strategy.entry('Short', strategy.short, alert_message = "GoShort")
// Plot the signals and compare them with the Alerts log
plotshape(series=longCondition, title="Long", text="Long", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
plotshape(series=shortCondition, title="Short", text="Short", style=shape.triangledown, location=location.belowbar, color=color.red, size=size.small)
Edit 2: The 2nd approach also created an alert despite there not being any signal plotted. Screenhot here
You should test also with strategy.opentrades which will return something !=0 if a trade (Long or Short) is currently open :
if longCondition and strategy.opentrades==0
strategy.close_all(comment="close", immediately=true)
strategy.entry('Long', strategy.long, alert_message = "GoLong")
if shortCondition and strategy.opentrades==0
strategy.close_all(comment="close", immediately=true)
strategy.entry('Short', strategy.short, alert_message = "GoShort")

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

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)

How to add all or some conditions to alert ? - Pine script tradingview

I have a list of conditions for a candle. This is just an example:
aa = (close > open) and (low > low[1])
bb = (close[1] > open[1]) and (close[1] > 5)
cc = (close > ((high[1] - low[1])*23.6/100 + low[1]))
dd = (close > EMA34) and (close > ema(close, 10))
I set alert using the following code:
if aa
alert("A- " + tostring(close, "#.######"), alert.freq_once_per_bar)
else if bb
alert("B- " + tostring(close, "#.######"), alert.freq_once_per_bar)
else if cc
alert("C- " + tostring(close, "#.######"), alert.freq_once_per_bar)
else if dd
alert("D- " + tostring(close, "#.######"), alert.freq_once_per_bar)
With each condition, I will get an alert with a letter at the beginning of the message so I can know the priority of the conditions, ie A is the best, D is the last one.
I would like to know if there is any way to check all conditions at the same time, so I can set the priority like:
if the alert has all conditions fulfilled, so it's the best A
if the alert has at least 3 conditions fulfilled, then it's B
if the alert has at least 2 conditions, then it's C
and if there is only 1 condition fulfilled, then it will be D
The real list has more than 10 conditions so I cannot check them manually. Please give me some code to do it programmatically.
I think, it's something related to array but I don't know how to do it.
Thank you for helping me.
aa = (close > open) and (low > low[1]) ?1:0
bb = (close[1] > open[1]) and (close[1] > 5) ?1:0
cc = (close > ((high[1] - low[1])*23.6/100 + low[1])) ?1:0
dd = (close > EMA34) and (close > ema(close, 10)) ?1:0
number_of_condition_true=aa+bb+cc+dd
bool all_condition_true=na
bool three_condition_true=na
bool two_condition_true=na
bool one_condition_true=na
bool none_condition_true=na
if number_of_condition_true>=4
all_condition_true:=true
else if number_of_condition_true>=3
three_condition_true:=true
else if number_of_condition_true>=2
two_condition_true:=true
else if number_of_condition_true>=1
one_condition_true:=true
else if number_of_condition_true==0
none_condition_true:=true
this is one of the ways ,this code will help you in programming your logic. in the above code i have replaced it into numerical value if true , than i have added all , this will give you the overall how may are true at a time.

Script for indicating order history - Tradeview Pine

I want to indicate historical trades in tradingview charts via a script based on information on time and price for entry and close.
My best idea is to search through "time" to find matches for entry and close, and then change the background color according to short or long position or draw a horizontal line. However, this seems not optimal. Any suggestions?
I'd implement that in the next way:
//#version=3
strategy("Background changing", overlay=true)
NONE = 0
LONG = 1000
SHORT = -1000
position = NONE
position := nz(position[1], NONE)
longCondition = crossover(sma(close, 14), sma(close, 28))
if (longCondition)
strategy.entry("LongEntryId", strategy.long)
position := LONG
if (close < high[1])
strategy.close("LongEntryId")
position := NONE
getColor(state) =>
state == LONG ? green :
state == SHORT ? red :
white
bgcolor(color=getColor(position))
Or you can put arrows to the chart:
//#version=3
study("My Script", overlay=true)
order = 0
if time >= timestamp(2018, 1, 10, 0, 0)
order := 1
if time == timestamp(2018, 1, 17, 0, 0)
order := -1
plotarrow(order)