Risk Management: If already long then do not place new order - algorithmic-trading

If the flag is already indicating long, there should not be a new flag indicating long. If flag does not indicate long evaluate the expression
longCondition = if (strategy.long) ? false: (rsi<30) and (close>moving_avg)
shortCondition = if (strategy.short) ? false: (rsi>70) and (close<moving_avg)
Processing script...
line 30: mismatched input 'shortCondition' expecting 'end of line
without line continuation'

I assume this is an indicator and not a strategy. Because you can configure how many entries you want to have in the same direction in a strategy with the pyramiding parameter. Default is 0, so if this is a strategy and you haven't changed the pyramiding parameter, it shouldn't be a problem.
For indicators, you can use a variable like this:
//#version=4
study("My Script", overlay=true)
var isLong = false
var isShort = false
rsi = rsi(close, 14)
moving_avg = ema(close, 9)
buySignal = not isLong and (rsi<50) and (close>moving_avg) // Buy only if we are not already long
sellSignal = not isShort and (rsi>50) and (close<moving_avg) // Sell only if we are not already short
if buySignal
isLong := true
isShort := false
if sellSignal
isLong := false
isShort := true
plotshape(series=buySignal, title="BUY", text="BUY", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
plotshape(series=sellSignal, title="SELL", text="SELL", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small)

Related

Writing memory bit value - TwinCat 2

I've been trying to write values to memory bits if certain conditions are verified, but so far not very successfully. In the piece of code presented below I have 3 variables which I've set to 1, therefore the condition returns the value TRUE (I've tested this). However, the values of variables "M_ALARME_BENCH_STOP" and "M_ALARME_BENCH_WARN" (memory bits) do not comute to the desired values. What am I doing wrong/missing?
IF ((S_DHW_IN_TP = 1) AND (IU_DHW_IN_TP = 1) AND (C_DHW_IN_TP = 1)) THEN
M_ALARME_BENCH_STOP := TRUE;
M_ALARME_BENCH_WARN := FALSE;
ELSIF ((S_DHW_IN_TP = 0) AND (IU_DHW_IN_TP = 1) AND (C_DHW_IN_TP = 1)) THEN
M_ALARME_BENCH_WARN := TRUE;
M_ALARME_BENCH_STOP := FALSE;
ELSE
M_ALARME_BENCH_WARN := FALSE;
M_ALARME_BENCH_STOP := FALSE;
END_IF
The piece of code you provided should work as you described. Are you sure, that these 2 variables are not being set somewhere else in your code after this IF statement?
You can check it by placing a breakpoint directly after END_IF. If they are set to desired values on the breakpoint, then they are probably reset somewhere else.

Ticker labels after plot

I would really appreciate some help adding a ticker label after my plot from the code below. Below is an extract of the main code - I've only used the lines for 1 ticker but in reality, I'll have 32 symbols in total so I've omitted the unnecessary code duplication for the other tickers for the purposes of this query.
Any improvements on the rest of the code would also be appreciated. I'm using ticker.new as 1) I don't need the inputs and the plot only seemed to display properly when the session was listed as extended (even though the chart was already set to extended)
//#version=5
indicator('NASDAQ Trend', overlay=true)
// SYMBOLS //
s01 = ticker.new("NASDAQ", "AAL", session.extended)
// CALCULATIONS //
screener_func() =>
//STACKED EMAs
MA1 = ta.ema(close, 5)
MA2 = ta.ema(close, 8)
MA3 = ta.ema(close, 13)
MA4 = ta.ema(close, 21)
MA5 = ta.ema(close, 34)
MA_Stack_Up = (MA1 > MA2) and (MA2 > MA3) and (MA3 > MA4) and (MA4 > MA5)
//CONDITIONS
Uptrend = MA_Stack_Up
Reversal = ((MA1 < MA2) and (MA2 > MA3)) or ((MA1 > MA2) and (MA2 < MA3))
//COLOR CODING
Bar_Color = Uptrend ? color.new(color.green, 25) : Reversal ? color.new(color.yellow, 25) : color.new(color.red, 25)
[Bar_Color]
// Security call
[TS01]= request.security(s01, timeframe.period, screener_func())
// PLOTS //
l_width = 3
shape = plot.style_circles
plot(1, color=TS01, style=shape, linewidth=l_width)
//LABELS//
L1= label.new(bar_index, 1, text=s01, style=label.style_none, textcolor=color.new(color.white, 0), size=size.small)
label.delete(L1[1])
My problem is the resulting label is ={"session":"extended","symbol":"NASDAQ:AAL"}. Ideally, the label should be just AAL
You can write a function that extracts the part you are interested from that string. If your string ALWAYS has the same format ={"session":"extended","symbol":"NASDAQ:AAL"}.
Step 1: Split the string using : as a delimeter. You will then have 4 sub strings.
={"session"
"extended","symbol"
"NASDAQ
AAL"} <-- This is what you want (index: 3)
Step 2: Remove the last two chars. Since the last two chars will always be "}, return a string until last two chars.
getName(_str) =>
string[] _pair = str.split(_str, ":")
string[] _chars = str.split(array.get(_pair, 3), "") // Index 3
int _len = array.size(_chars) - 2 // Don't get the last two chars
string[] _substr = array.new_string(0)
_substr := array.slice(_chars, 0, _len)
string _return = array.join(_substr, "")
Then call this function when you create a label:
//LABELS//
L1= label.new(bar_index, 1, text=getName(s01), style=label.style_none, textcolor=color.new(color.white, 0), size=size.small)
label.delete(L1[1])
No sense in doing all those string gymnastics when the ticker is available. Try this:
//#version=5
indicator('NASDAQ Trend', overlay=true)
// CALCULATIONS // {
// hey look – it's now foldable....
screener_func() =>
// STACKED EMAs
MA1 = ta.ema(close, 5)
MA2 = ta.ema(close, 8)
MA3 = ta.ema(close, 13)
MA4 = ta.ema(close, 21)
MA5 = ta.ema(close, 34)
// CONDITIONS - no sense in allocating extra variables when hidden in function
Uptrend = (MA1 > MA2) and (MA2 > MA3) and (MA3 > MA4) and (MA4 > MA5)
Reversal = ((MA1 < MA2) and (MA2 > MA3)) or ((MA1 > MA2) and (MA2 < MA3))
// DETERMINE COLOR CODING - just return the results
// vs assigning to a variable and then return the variable...
[Uptrend ? color.new(color.green, 25) : Reversal ? color.new(color.yellow, 25) : color.new(color.red, 25)]
// }
// Define tickers and set up labels on last bar
// Note: request security limits the max number of tickers to 40
var tickers = array.from("AA","AAL","AAPL")
// use the index of the symbol in the ticker array as price level to plot...
if barstate.islast
for item in tickers
label.new(bar_index+ 5, array.indexof(tickers,item), item, style=label.style_none, textcolor=color.new(color.white, 0), size=size.small)
// Since the ticker symbol must be know at complile time aka simple string,
// we have to call each symbol separately - what a pain...
// style variations here in case we want to change
var aStyle = plot.style_circles
var aLinewidth = 3
// AA <-- Yep this is definitely not NASDAQ material...
temp1 = ticker.new("NYSE", "AA", session.extended)
[temp2] = request.security(temp1, timeframe.period, screener_func())
plot(0, color= temp2, style=aStyle, linewidth=aLinewidth)
// AAL
temp3 = ticker.new("NASDAQ", "AAL", session.extended)
[temp4] = request.security(temp3, timeframe.period, screener_func())
plot(1, color= temp4, style=aStyle, linewidth=aLinewidth)
// AAPL
temp5 = ticker.new("NASDAQ", "AAPL", session.extended)
[temp6] = request.security(temp5, timeframe.period, screener_func())
plot(2, color= temp6, style=aStyle, linewidth=aLinewidth)
output image

VB6: Double buffering/stop flickering on a movement animation

Currently I have 6 images layered over top of each other, each with their own corresponding walk animation frame. Each time you walk the Visible property changes and allows the next animation frame to be seen.
The only problem is the bloody flickering when it is passing through any type of object be it, picturebox, form, command button, etc....
After a tiresome day of research I just can't come up with a solution to fix this.
a little snippet of my code if anyone want's to see:
Select Case CharFrame
Case 1
Avatar(0).Visible = True
Avatar(1).Visible = False
Avatar(2).Visible = False
CharFrame = CharFrame + 1
Case 2
Avatar(0).Visible = False
Avatar(1).Visible = True
Avatar(2).Visible = False
CharFrame = CharFrame + 1
Case 3
Avatar(0).Visible = False
Avatar(1).Visible = False
Avatar(2).Visible = True
CharFrame = 1
End Select
Sleep (Timer)
Avatar(0).Top = Avatar(0).Top + moveY
Avatar(1).Top = Avatar(1).Top + moveY
Avatar(2).Top = Avatar(2).Top + moveY
Avatar(3).Top = Avatar(0).Top
Avatar(4).Top = Avatar(1).Top
Avatar(5).Top = Avatar(2).Top
Avatar(6).Top = Avatar(0).Top
Avatar(7).Top = Avatar(1).Top
Avatar(8).Top = Avatar(2).Top
Avatar(9).Top = Avatar(0).Top
Avatar(10).Top = Avatar(1).Top
Avatar(11).Top = Avatar(2).Top
Loop
Avatar(0).Visible = True
Avatar(1).Visible = False
Avatar(2).Visible = False
Found this with Google:
Private Declare Function LockWindowUpdate Lib "USER32" (ByVal hwndLock As Long) As Long
When you like to stop window updating:
LockWindowUpdate <yourform>.hWnd
If you like to continue
LockWindowUpdate False
Found this, did not try it.

For loop won't end. Don't know why

I'm writing a for loop for a project that prompts the user to input a number and keeps prompting, continually adding the numbers up. When a string is introduced, the loop should stop. I've done it with a while loop, but the project states that we must do it with a for loop also. The problem is that the prompt keeps running even when 'a = false'. Could someone explain javascript's thinking process? I want to understand why it keeps running back through the loop even though the condition isn't met. Thank you
var addSequence2 = function() {
var total = 0;
var a;
for (; a = true; ) {
var input = prompt("Your current score is " +total+ "\n" + "Next number...");
if (!isNaN(input)) {
a = true;
total = +total + +input;
}
else if (isNaN(input)) {
a = false;
document.write("Your total is " + total);
}
}
};
There is a difference between a = true and a == true.
Your for-loop is basically asking "can I set 'a' to true?", to which the answer is yes, and the loop continues.
Change the condition to a == true (thus asking "Is the value of 'a' true?")
To elaborate, in most programming languages, we distinguish between assignment ("Make 'x' be 4") and testing for equality ("Is 'x' 4?"). By convention (at least in languages that derive their syntax from C), we use '=' to assign/set a value, and '==' to test.
If I'm understanding the specification correctly (no guarantee), what happens here is that the condition condenses as follows:
Is (a = true) true?
Complete the bracket: set a to true
Is (a) true? (we just set it to true, so it must be!)
Try using the equal to operator, i.e. change
for (; a = true; ) {
to
for (; a == true; ) {
You should use a == true instead of a = true......= is an assignment operator
for (; a = true; ), you are assigning the value to the variable "a" and it will always remain true and will end up in infinite loop. In JavaScript it should a===true.
I suspect you want your for to look like this :
for(;a==true;)
as a=true is an assignment, not a comparison.
a == true. The double equal sign compares the two. Single equal assigns the value true to a so this always returns true.
for (; a = true; ) <-- this is an assignation
for (; a == true; ) <-- this should be better
Here's your fixed code :
var addSequence2 = function() {
var total = 0;
var a = true;
for(;Boolean(a);) {
var input = prompt("Your current score is " +total+ "\n" + "Next number...");
if (!isNaN(input)) {
total = total + input;
}
else{
a = false;
document.write("Your total is " + total);
}
}
};

R: tm Textmining package: Doc-Level metadata generation is slow

I have a list of documents to process, and for each record I want to attach some metadata to the document "member" inside the "corpus" data structure that tm, the R package, generates (from reading in text files).
This for-loop works but it is very slow,
Performance seems to degrade as a function f ~ 1/n_docs.
for (i in seq(from= 1, to=length(corpus), by=1)){
if(opts$options$verbose == TRUE || i %% 50 == 0){
print(paste(i, " ", substr(corpus[[i]], 1, 140), sep = " "))
}
DublinCore(corpus[[i]], "title") = csv[[i,10]]
DublinCore(corpus[[i]], "Publisher" ) = csv[[i,16]] #institutions
}
This may do something to the corpus variable but I don't know what.
But when I put it inside a tm_map() (similar to lapply() function), it runs much faster, but the changes are not made persistent:
i = 0
corpus = tm_map(corpus, function(x){
i <<- i + 1
if(opts$options$verbose == TRUE){
print(paste(i, " ", substr(x, 1, 140), sep = " "))
}
meta(x, tag = "Heading") = csv[[i,10]]
meta(x, tag = "publisher" ) = csv[[i,16]]
})
Variable corpus has empty metadata fields after exiting the tm_map function. It should be filled. I have a few other things to do with the collection.
The R documentation for the meta() function says this:
Examples:
data("crude")
meta(crude[[1]])
DublinCore(crude[[1]])
meta(crude[[1]], tag = "Topics")
meta(crude[[1]], tag = "Comment") <- "A short comment."
meta(crude[[1]], tag = "Topics") <- NULL
DublinCore(crude[[1]], tag = "creator") <- "Ano Nymous"
DublinCore(crude[[1]], tag = "Format") <- "XML"
DublinCore(crude[[1]])
meta(crude[[1]])
meta(crude)
meta(crude, type = "corpus")
meta(crude, "labels") <- 21:40
meta(crude)
I tried many of these calls (with var "corpus" instead of "crude"), but they do not seem to work.
Someone else once seemed to have had the same problem with a similar data set (forum post from 2009, no response)
Here's a bit of benchmarking...
With the for loop :
expr.for <- function() {
for (i in seq(from= 1, to=length(corpus), by=1)){
DublinCore(corpus[[i]], "title") = LETTERS[round(runif(26))]
DublinCore(corpus[[i]], "Publisher" ) = LETTERS[round(runif(26))]
}
}
microbenchmark(expr.for())
# Unit: milliseconds
# expr min lq median uq max
# 1 expr.for() 21.50504 22.40111 23.56246 23.90446 70.12398
With tm_map :
corpus <- crude
expr.map <- function() {
tm_map(corpus, function(x) {
meta(x, "title") = LETTERS[round(runif(26))]
meta(x, "Publisher" ) = LETTERS[round(runif(26))]
x
})
}
microbenchmark(expr.map())
# Unit: milliseconds
# expr min lq median uq max
# 1 expr.map() 5.575842 5.700616 5.796284 5.886589 8.753482
So the tm_map version, as you noticed, seems to be about 4 times faster.
In your question you say that the changes in the tm_map version are not persistent, it is because you don't return x at the end of your anonymous function. In the end it should be :
meta(x, tag = "Heading") = csv[[i,10]]
meta(x, tag = "publisher" ) = csv[[i,16]]
x

Resources