PineScript is exiting strategy and opening a double sized order on the same bar - trading

Using the pinescript editor in TradingView, I've noticed a slightly strange occurrence. When there are triggers to exit a long trade (trailing stop) and a trigger to enter a new short trade on the same bar, both open, however, the short has 2x the position size than it should.
Here's the relevant code:
// When uptrend, use upper band as a stop market buy
if (uptrend)
strategy.entry("Long", strategy.long, stop = h)
// Exit longs with a trailing stop. Assume longStopPrice is calculated per bar
if (strategy.position_size > 0)
strategy.exit("Trailing Stop", "Long", stop = longStopPrice)
// When downtrend, use lower band as a stop market sell
if (downtrend)
strategy.entry("Short", strategy.short, stop = l)
// Exit shorts with a trailing stop. Assume shortStopPrice is calculated per bar
if (strategy.position_size < 0)
strategy.exit("Trailing Stop", "Short", stop = shortStopPrice)
Here is the output on the UI:
Notice that the long position size is 15.358918 and a few bars later, this is closed with a trailing stop size -15.358918. However a new short trade is also opened on the same bar size -30.70059 (It should not be -30 it should be -15).
A little bit later on this second trade is closed by trailing stop, size +15.34 (but -30 was opened).
The strategy leaves you net short -15 units for the entire duration of the backtest. Ideally i'd like the strategy.enter to only enter a single position size & trailing stop to close the entire position, not to enter a double position & close half.
Any ideas?

Its because your exit condition does not have the same id as the entry condition. For TV, the entry id has still not closed. So, change the exit id from 'Trailing Stop' to 'Long' and 'Short' as those are the ids used during the entry.

Theres some logic behind but this happens when you dont close a position before opening a new one, what helped me was just moving the close strategy above the open, so every loop also checks to confirm to always close a position before opening a new one
Btw, also dont forget that on one way mode position your 2nd trade must have to be 2x the previous one, since lets say you go +$25 long, then -$25 for short, you would end with $0 for the next trade. Then having 2x the previous one, you would go +$25 long, then -$50 for short, you would end with -$25 short for your next trade, then +$50 long again you would end +$25 next trade

add to if downtrend this--
and strategy.position_size == 0

Related

How to look back a certain number of days for an indicator and how to only calculate logic upto the last complete bar (i.e. not the current bar)

I'm relatively new to Pine and was having trouble with a couple of things.
So I've got a indicator that I want to look back for the last 5 full days of activity, however not each stock trades in the premarket/afterhours so I want to be able to look back say 5 days and then calculate the number of bars on the time frame (i.e. for a 5 min or hourly resolution). That way I can calculate the number of bars present on the current ticker for that time frame and adjust my indicator length (instead of just having a constant figure of 80 bars or whatever).
The second thing I want to do is only have the indicator update on the completion of a full bar (for example the hourly resolution). So I want it to only calculate up to x-1 bars. Right now I'm finding that it's updating on each new tick. ( I was able to figure this one out, just changed it from i= 0 to length -1 to i=1 to length).
Any help is greatly appreciated.
Thanks,
A

ANSI control sequence: after setting line home and limit, how should cursor movements behave? which coordinates to use?

Context:
I'm working on a device which inserted between an electronic typewriter's controller and its keyboard turns it into a serial printer/terminal.
I want it to support some of the control sequences from ECMA-48 / ISO-6429 / ANSI X3.64. (also known as ANSI escape code)
I'm having some uncertainty if I'm understanding correctly the standard, so I would like to ask to know how it should be.
It's related to the commands SLH - SET LINE HOME and SLL - SET LINE LIMIT.
For example I could have the situation that I have 1/12 inch wide characters, I want a left margin of 1 inch, and 80 columns of text.
Then I would set page home to 13 and page limit to 92.
(since character positions are counted from 1, home is the first position, limit is the last)
So far ok.
But when I already have set the home, than how should the functions:
CHA - CURSOR CHARACTER ABSOLUTE
CUP - CURSOR POSITION
HPA - CHARACTER POSITION ABSOLUTE
CPR - ACTIVE POSITION REPORT
and others related to the cursor position work?
Should they use coordinates relative to to the actual edge, or to the home position.
So in my above example if I wanted to move to column 2 of the text print area (home being 13), I should use coordinate 2 or 14?
(similarly for vertical position and page home & limit)
My understanding is that these control sequences still use the absolute coordinates.
so in my example I would have to use coordinate 14.
Is this correct?
And if it is correct, this raises some additional problems:
I would have to know where the margins are to know which horizontal and vertical offset to use when moving the cursor to absolute positions.
If a program sets the margins first, then no problem, but I a program connects to the device and does not change the margins then it does not know the offset.
(There is a way, it could send a carriage return to move to the home position and then request the ACTIVE POSITION REPORT to discover the left margin position, but it does not look like a nice solution)
What should my device do if it is requested to move to a position outside the defined home and limit?
The standard says that beyond these limits no implicit movement should happen, but this is explicit movement.
If it receives a command to move to position 1 when the home is 13 what should it do? Move to 1? Move to 13? ignore?
When it is at position 15, home is at 13 and receives command to move cursor left by 4 positions should it move by 4 to 11? move by 2 to 13? ignore?
Another problem I see is that there is a command to set page home, and page limit, but not total page height.
It is only possible to select predefined formats by PFS - PAGE FORMAT SELECTION.
But I don't see a way to select any other height.
If I want to use continuous paper with 12 inch long pages (72 lines of text at 1/6 inch line height) connected together into a long tape then I see no way to define that height so that my device can correctly keep track of its positions on the following pages. Is there a way to do it?
Looks like I had to find the answers by myself.
question 0:
Yes, it appears, that the coordinates should still be absolute.
he standard says about character positions in a line and line positions in a page and these are specified in the beginning of the document and nowhere at all is said about it being relative. Looks like the only role of line home and limit is the place where CR (and some others) returns to, and limit of where implicit movement (like advancing forward after printing a character) can go, similar for page home and page limit.
question 1:
There is no easy way for a program to recognise where the home and limit positions are. As I mentioned, requesting ACTIVE POSITION REPORT can help if this is implemented. (my devece does not support it yet).
Anyway, many programs don't recognise the concept of line home, and assume that normal character positions start from 1.
My solution to this is that after power on, the line home IS exactly at position 1, and if you want something else, you have to specify it.
This way a program can safely make this assumption.
(However after the PFS - PAGE FORMAT SELECTION command I do set the line home to 1 inch as this is what the standard proposes)
question 2:
As above, the home and limit are only a margin for implicit movements. So the cursor movement commands will move outside these limits with no problem. Only the actual page size will limit them.
question 3:
(but I didn't give it a number when asked)
DTA - DIMENSION TEXT AREA is the command for this purpose. It specifies the size of the text area limited by the actual page size, not by the home and limit positions.

Open a trade when an indicator places an arrow in a chart

Is it possible for an EA to open a trade when an indicator places an arrow on the current candle or a previous candle? If yes, how?
I have an indicator that places an arrow where a trade say a BUY or a SELL can be placed. I know that we use code below to get the values of the signal.
double signal_v = iCustom(Symbol(),PERIOD_M1, "My Custom Indicator", 0, 1);
The indicator in this question places an arrow, and I want to know if there is a way one can tell if an arrow has been placed on the current or previous candle by this specific indicator. I have seen any sample codes so I was asking. Kindly.
1 in your example is number of bar (0 - current, 1 - previous one), 0 is the buffer.
For sure you will have at least two buffers if arrows are implemented from buffers (easy to check - open chart and delete all objects. if arrows stay there - then indicator has buffers and arrows are based on buffers. Open data window and check the bar that has an arrow - it must have value in some buffer line that is not zero and not empty, you can compare to other bars with no buffers.
Do not forget that you have to pass all indicator inputs after "My Custom Indicator" otherwise you will upload the indicator with default settings, not what you need.

Are MT4 Strategy Tester backtest results panel dates somehow linked with MT4 Graph?

when I see the backtest results, there is a Result panel( Ref. e.g.: https://quivofx.com/wp-content/uploads/2015/02/result.png )
that listed all transactions for the backtest.
Is there a way to quickly scroll to the relevant portion of the graph?
For example, say buy on 2017.05.03 10.30 EURUSD 5 Min, I would scroll to that portion by just e.g., double click on the entry?
Currently, it is pretty slow for me to go back and forth to check for result entries by scrolling the Graph manually.
double click on trade entry or modification or exit and you will see that picture (of course if you ran the test with visual mode=true)
press space bar and type data and time then press enter - you will see that the chart moves to the indicated date
Another fast & built-in method available:
The fastest jump to an exact datetime value in the MT4 Graph works via the mouse double-click inside the graph's time scale area, near the lower-left corner, where a small gray triangle is present.
A mouse, positioned there for a while, shows a self-explanatory label Double click for editing
Next, one may type-in or copy/paste there any datetime target as one wishes to move to.
2016-12-12 08:00
and hit ENTER
So,
1) using mouse-select ( over a legitimate datetime value as seen in Strategy Tester results et al )
2) Ctrl-INS to copy into a paste buffer
3) Alt-TAB to get into MetaTrader Terminal 4 Graph, if Results were copied from WebBrowser, not from a Strategy Tester sub-window panel in MT4
4) using a mouse-doubleclick activate the datetime entry field as explained above
5) Shift-INS to paste the paste-buffer content
6) ENTER & voila, you are there.

AS2 - Display game results at end of level

I'm currently making a maze game at the minute, and I want to include a death counter and a count-up timer. When the level is over, I want the game to display the time taken and the number of deaths made. How can I make it save the death count, and display it at the end?
On your first frame, declare these two variables which will hold the number of deaths and count up (paste the code on your Frame actions):
var deaths = 0;
var time = 0;
Now, whenever the player dies, use this code to increase the death count:
deaths++;
When you want to start the timer, paste this code on the frame where the game begins:
function countUp(){
time++;
}
setInterval(countUp, 1000);
This will run the function every 1000th milliseconds, which is the same as every second (1000 milliseconds = 1 second). The function itself increases the time variable by 1, but it does not display it on the screen.
Now, on the results screen, you first have to make two Dynamic Text Fields (create a text field, open the Properties Panel [CTRL+F3], and change it from Static text to Dynamic text). Give these two Dynamic text fields the instance names of, death_txt and timer_txt, respectively. Then, paste this code on the frame actions of the results screen:
death_txt.text = deaths;
timer_txt.text = time;
This will make them show up on the screen.
By the looks of it, it doesn't seem like you're familiar with variables, but they're nothing but containers which contain values. You can control them "behind the scenes", meaning that you can calculate, store and change them in Flash without them appearing on the screen. This is useful since you don't want the death count and count up to actually be shown during gameplay, right?
If you need more clarficiation, please don't hesitate to ask.
Hope this helps :)

Resources