Pine script - using buy limit/sell limit is not firing at an exact price - pine-script-v5

I am trying to enter using a buy limit order at an exact price using pine script eg. 146.090 but even though the price has gone under and over it - it still does not execute.
I do not want to use close/high/low etc, just the exact price.
It would be greatly appreciated if somebody had a workaround for the issue.
Thx.
//#version=5
VERSION = "V1"
SCRIPT_NAME = "Test " + VERSION
InitCapital = 100000
InitPosition = 100.0
InitCommission = 0.025
InitPyramidMax = 1
CalcOnorderFills = false
ProcessOrdersOnClose = true
CalcOnEveryTick = true
CloseEntriesRule = "FIFO"
strategy(title=SCRIPT_NAME, shorttitle=SCRIPT_NAME, overlay=true, pyramiding=InitPyramidMax, initial_capital=InitCapital, default_qty_type=strategy.fixed, process_orders_on_close=ProcessOrdersOnClose, default_qty_value=InitPosition, commission_type=strategy.commission.percent, calc_on_order_fills=CalcOnorderFills, calc_on_every_tick=CalcOnEveryTick, precision=9, max_lines_count=500, max_labels_count=500, commission_value=InitCommission)
var float entry = 145.606
strategy.entry("Long", strategy.long, limit=entry)

Try to replace :
strategy.entry("Long", strategy.long, limit=entry)
By :
strategy.entry("Long", strategy.long, limit=entry, close=entry)

Related

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

Code not plotting - Function should be called on each calculation for consistency. It is recommended to extract the call from this scope"

I am getting this as an orange error - not sure what I have done wrong or whether this error is the reason that the code doesn't plot. I am brand new to Pine-script and any assistance would be invaluable. Many thanks in advance Alastair
//#version=5
indicator("PCY TEST4")
//Get User Inputs
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
src = input(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
//Variables
a = 0.33
PCY = 0.0
PCYi = 0.0
// Calculating
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
minMacd=0.0
for i = 0 to (signal_length[1])
minMacd := ta.min(macd)
maxMacd=0.0
for i = 0 to (signal_length[1])
maxMacd := ta.max(macd)
//maxMacd = ta.min(macd)
//minMacd = ta.max(macd)
//signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
//hist = macd - signal
delta = maxMacd-(fast_ma - slow_ma)/(maxMacd -minMacd)
for i = 0 to (signal_length)
PCYi := a*((delta - PCYi[1])+PCYi[1])
PCYi
//Plotting
plot(PCYi)
I think it's because you're calculating the min/max in a for loop
Those functions should (not mandatory but strongly recommended) be calculated at every candle instead
for i = 0 to (signal_length[1])
minMacd := ta.min(macd)
maxMacd=0.0
for i = 0 to (signal_length[1])
maxMacd := ta.max(macd)
If you want to calculate the min/max over a X period of time, maybe use the ta.highest/ta.lowest functions instead :)
And of course, those 2 should be called at every candle (i.e. not in a if, for,... statement)

pinescript strategy - different result after script translation v2>v5

v2vsv5i have a simple script , translate the version from v2 > v5 , it should be sucess and work on new ver.v5 but i face a problem that , the strategy entry/exit time is totally different after translate.(refer to photo,should clearly show the different) i double check the script and setting, should be no bug. (you can see the quantity of trade no. are same)
what i guess and want---
is it possible there is problem,some of internal-pine-script-fuction - logic which is different from v5 vs v2?
How to modify the v5 version script in order to get the same result(same strategy entry/exit time) with v2?
Printscreen here:
https://i.imgur.com/6KLSjnJ.gif
https://i.imgur.com/6KLSjnJ.gif
v2 script:
'//Heikin Ashi Strategy
strategy("Heikin Ashi",shorttitle="HA_R01",overlay=true,default_qty_value=1000,initial_capital=100000,currency=currency.USD)
res = input(title="Heikin Ashi Candle Time Frame", type=resolution, defval="1440")
hshift = input(0,title="Heikin Ashi Candle Time Frame Shift")
//Heikin Ashi Open/Close Price
ha_t = heikinashi(tickerid)
ha_open = security(ha_t, res, open[hshift])
ha_close = security(ha_t, res, close[hshift])
//Strategy
golong = (ha_close > ha_open )
goshort = (ha_close < ha_open )
strategy.entry("Buy",strategy.long,when = golong)
strategy.entry("Sell",strategy.short,when = goshort)
v5 script:
//Heikin Ashi Strategy
//#version=5
strategy("Heikin Ashiv5",shorttitle="HA_R01v5",overlay=true,default_qty_value=1000,initial_capital=100000,currency=currency.USD)
res = input.timeframe(title="Heikin Ashi Candle Time Frame", defval="D")
hshift = input(0,title="Heikin Ashi Candle Time Frame Shift")
//Heikin Ashi Open/Close Price
ha_t = ticker.heikinashi(syminfo.tickerid)
ha_open = request.security(ha_t, res, open[hshift])
ha_close = request.security(ha_t, res, close[hshift])
//Strategy
golong = (ha_close > ha_open )
goshort = (ha_close < ha_open )
strategy.entry("Buy",strategy.long,when = golong)
strategy.entry("Sell",strategy.short,when = goshort)here

Buy and sell-markers on lower time frames when longer time frame shows uptrend

So, I'm trying to run a trading bot on medium timeframes (1h - 4h) using the KDJ-indicator. I know it's not the most responsive indicator but it is very reliable, at least on higher time frames (8h - 1D).
What I would like to be able to do is use the following script to send BUY/SELL-signals to my bot, BUT ONLY when the asset is not trending down on the 1D-chart. In other words, I would like to run this script:
//#version=4
study(title="KDJ IndicatorTV", shorttitle="KDJ_TV", format=format.price, precision=2, resolution="", overlay=true)
periodK = input(9, title="K", minval=1)
periodD = input(5, title="D", minval=1)
smoothK = input(3, title="Smooth", minval=1)
multiplierJ = input(3.5, title="Jx", minval=0.1)
k = ema(stoch(hlc3, high, low, periodK), smoothK)
d = ema(k, periodD)
j = multiplierJ * k-2 * d
makeShape1 = if (crossover(j,d) or crossover(j,99))
true
else
false
plotshape(series=makeShape1, style=shape.cross, color=#0094FF, transp=10, text="buy", title='buy')
makeShape2 = if (crossunder(j,d) or crossunder(j,99))
true
else
false
plotshape(series=makeShape2, style=shape.cross, color=#FF6A00, transp=10, text="sell", title='sell')
//end
And I would like to add a condition to makeShape1, something like "AND If j>d on 1D-chart", to ensure that buys are only generated while J is larger than D on the 1D-chart of that asset (ie: when the market for that asset is in an uptrend).
Any ideas on if/how I can achieve that?
Thanks!
-Daniel
You can access higher TFs with security() function
//#version=4
study(title="KDJ IndicatorTV", shorttitle="KDJ_TV", format=format.price, precision=2, resolution="", overlay=true)
periodK = input(9, title="K", minval=1)
periodD = input(5, title="D", minval=1)
smoothK = input(3, title="Smooth", minval=1)
multiplierJ = input(3.5, title="Jx", minval=0.1)
k = ema(stoch(hlc3, high, low, periodK), smoothK)
d = ema(k, periodD)
j = multiplierJ * k-2 * d
j_sec = security(syminfo.tickerid, "D", j) // 1 day time frame for j
d_sec = security(syminfo.tickerid, "D", d) // 1 day time frame for d
makeShape1 = if (crossover(j,d) or crossover(j,99)) and j_sec > d_sec
true
else
false
plotshape(series=makeShape1, style=shape.cross, color=#0094FF, transp=10, text="buy", title='buy')
makeShape2 = if (crossunder(j,d) or crossunder(j,99))
true
else
false
plotshape(series=makeShape2, style=shape.cross, color=#FF6A00, transp=10, text="sell", title='sell')
//end

In Pine Script, how can you do something once per day, or keep track if something has been done yet that day?

I'm working on a TradingView script (Pine) and i'm trying to use my Daily-bar strategy on the 5-minute chart. To do this, I need to basically only check conditions once per day.
I can do this by having a boolean variable such as dailyCheck = false and set it to true when I run that code and then reset it on a new day.
Does anyone know how to go about doing this? From what I read in the pine manual it says you can get unix time...but I don't know how to work with this and I can't print anything except numbers in the form of plot, so I can't figure out how to tell when a new day has started. Thanks in advance!
Version 1
There are lots of ways to detect a change of day. The Session and time information User Manual page shows a few.
I like detecting a change in the dayofweek or dayofmonth built-in variables:
//#version=4
study("Once per Day")
var dailyTaskDone = false
newDay = change(dayofweek)
doOncePerDay = rising(close, 2) // Your condition here.
dailyTaskDone := doOncePerDay or (dailyTaskDone and not newDay)
plotchar(newDay, "newDay", "▼", location.top, transp = 60)
plotchar(doOncePerDay, "doOncePerDay", "•", location.top, transp = 0)
bgcolor(dailyTaskDone ? color.orange : na)
Version 2
Following Michel's comment, this uses a more robust detection of the day change:
//#version=4
study("Once per Day")
var dailyTaskDone = false
newDay = change(time("D"))
doOncePerDay = rising(close, 2) // Your condition here.
dailyTaskDone := doOncePerDay or (dailyTaskDone and not newDay)
plotchar(newDay, "newDay", "▼", location.top, transp = 60)
plotchar(doOncePerDay, "doOncePerDay", "•", location.top, transp = 0)
bgcolor(dailyTaskDone ? color.orange : na)
And for the OP, a v3 version:
//#version=3
study("Once per Day v3")
dailyTaskDone = false
newDay = change(time("D"))
doOncePerDay = rising(close, 2) // Your condition here.
dailyTaskDone := doOncePerDay or (dailyTaskDone[1] and not newDay)
plotchar(newDay, "newDay", "▼", location.top, transp = 60)
plotchar(doOncePerDay, "doOncePerDay", "•", location.top, transp = 0)
bgcolor(dailyTaskDone ? orange : na)