Creating a SL/TP based on ticks with flexible rules in Pinescript/Tradingview - trading

I have created a stop loss and take profit based on ticks
sl_inp = input.int(10, title='SL in Ticks')
tp_inp = input.int(10, title='TP in Ticks')
strategy.exit("Long Exit", "Long Entry", loss=sl_inp, profit=tp_inp)
The issue is that I can't figure out how to add additional rules around this.
For example, if candle closes above TP, leave position open and move SL to TP level.
Also I could just use the below to get the same outcome as above it seems but again, it doesn't help much.
strategy.exit("Long Exit", "Long Entry", loss=10, profit=10)
Thanks

You can't just move SL to TP level cause at the moment price close above it, the TP level is already hitted and position is closed.
Try this:
sl_inp = input.int(10, title='SL in Ticks')
tp_inp = input.int(10, title='TP in Ticks')
stopl = strategy.position_avg_price - sl_inp
if crossover(close, (strategy.position_avg_price + tp_inp))
stopl := strategy.position_avg_price + tp_inp
tp_inp := tp_inp + tp_inp
strategy.exit("Long Exit", "Long Entry", stop = stopl)
But this means that you TP wont work if it's simply touched.

Related

Can't calculate the right Volume RSI in MQL4 with a functioning Pine-Script Example

I want to "translate" a Pine-Script to MQL4 but I get the wrong output in MQL4 compared to the Pine-Script in Trading-view.
I wrote the Indicator in Pine-Script since it seems fairly easy to do so.
After I got the result that I was looking for I shortened the Pine-Script.
Here the working Pine-Script:
// Pinescript - whole Code to recreate the Indicator
study( "Volume RSI", shorttitle = "VoRSI" )
periode = input( 3, title = "Periode", minval = 1 )
VoRSI = rsi( volume, periode )
plot( VoRSI, color = #000000, linewidth = 2 )
Now I want to translate that code to MQL4 but I keep getting different outputs.
Here is the MQL4 code I wrote so far:
// MQL4 Code
input int InpRSIPeriod = 3; // RSI Period
double sumn = 0.0;
double sump = 0.0;
double VoRSI = 0.0;
int i = 0;
void OnTick() {
for ( i; i < InpRSIPeriod; i++ ) {
// Check if the Volume is buy or sell
double close = iClose( Symbol(), 0, i );
double old_close = iClose( Symbol(), 0, i + 1 );
if ( close - old_close < 0 )
{
// If the Volume is positive, add it up to the positive sum "sump"
sump = sump + iVolume( Symbol(), 0, i + 1 );
}
else
{
// If the Volume is negative, add it up to the negative sum "sumn"
sumn = sumn + iVolume( Symbol(), 0, i + 1 );
}
}
// Get the MA of the sump and sumn for the Input Period
double Volume_p = sump / InpRSIPeriod;
double Volume_n = sumn / InpRSIPeriod;
// Calculate the RSI for the Volume
VoRSI = 100 - 100 / ( 1 + Volume_p / Volume_n );
// Print Volume RSI for comparison with Tradingview
Print( VoRSI );
// Reset the Variables for the next "OnTick" Event
i = 0;
sumn = 0;
sump = 0;
}
I already checked if the Period, Symbol and timeframe are the same and also have a Screenshoot of the different outputs.
I already tried to follow the function-explanations in the pine-script for the rsi, max, rma and sma function but I cant get any results that seem to be halfway running.
I expect to translate the Pine-Script into MQL4.
I do not want to draw the whole Volume RSI as a Indicator in the Chart.
I just want to calculate the value of the Volume RSI of the last whole periode (when new candel opens) to check if it reaches higher than 80.
After that I want to check when it comes back below 80 again and use that as a threshold wether a trade should be opened or not.
I want a simple function that gets the Period as an input and takes the current pair and Timeframe to return the desired value between 0 and 100.
Up to now my translation persists to provide the wrong output value.
What am I missing in the Calculation? Can someone tell me what is the right way to calculate my Tradingview-Indicator with MQL4?
Q : Can someone tell me what is the right way to calculate my Tradingview-Indicator with MQL4?
Your main miss of the target is in putting the code into a wrong type of MQL4-code. MetaTrader Terminal can place an indicator via a Custom Indicator-type of MQL4-code.
There you have to declare so called IndicatorBuffer(s), that contain pre-computed values of the said indicator and these buffers are separately mapped onto indicator-lines ( depending on the type of the GUI-presentation style - lines, area-between-lines, etc ).
In case you insist on having a Custom-Indicator-less indicator, which is pretty legal and needed in some use-cases, than you need to implement you own "mechanisation" of drawing lines into a separate sub-window of the GUI in the Expert-Advisor-code, where you will manage all the settings and plotting "manually" as you wish, segment by segment ( we use this for many reasons during prototyping, so as to avoid all the Custom-Indicator dependencies and calling-interface gritty-nitties during the complex trading exosystem integration - so pretty well sure about doability and performance benefits & costs of going this way ).
The decision is yours, MQL4 can do it either way.
Q : What am I missing in the Calculation?
BONUS PART : A hidden gem for improving The Performance ...
In either way of going via Custom-Indicator-type-of-MQL4-code or an Expert-Advisor-type-of-MQL4-code a decision it is possible to avoid a per-QUOTE-arrival re-calculation of the whole "depth" of the RSI. There is a frozen-part and a one, hot-end of the indicator line and performance-wise it is more than wise to keep static records of "old" and frozen data and just update the "live"-hot-end of the indicator-line. That saves a lot of the response-latency your GUI consumes from any real-time response-loop...

Use ImageSearch to control the menus of Google Sheets

Did someone try to use ImageSearch to control the menus of google sheets? It's somehow failing me.
I simulated a right click on column A and then tried to find the option to change the size of the column with ImageSearch. I even put *n to 60 and that kind of worked but with the unpleasant side effect that it took at least 2 seconds for AutoHotkey to detect the image/word and then click on it. Does this work for your or do you have the same problem as me?
This is my ImageSearch function:
ImageSearchFunction(ImagePath){
start := A_TickCount
Loop {
ImageSearch, FoundX, FoundY, 0, 0, 1373, 775, *60 %ImagePath%
totalTime := stop - start
stop := A_TickCount
ClickX := FoundX + 15
ClickY := FoundY + 15
if ErrorLevel = 0
{
break
}
else if totalTime > 3000
{
MsgBox, Something went wrong!
exit
}
}
}
I solve it with a mousemove to the same place within the window every time and it works more consistently than image search did:
!e:: ; "Tools" is at x540 y245
{
CoordMode, Mouse, Relative
MouseMove, 540, 250,0
MouseGetPos, xpos, ypos
MouseClick
MouseMove, xpos, ypos+125,3
MouseClick
return
}
ImageSearch will work for a day or two and then just not work, no idea why. this one I have to adjust a lot less often.
edit. this script goes to "tools > script editor"

How to fix "Total canvas memory use exceeds the maximum limit (256MB)" error on iPad

I have a KonvaJS app with a "draw" functionality. On the mouse move event, I'm creating a new Line and adding points to it.
It works perfect on Desktop but it crashes on iPad. This is the issue that I get:
Total canvas memory use exceeds the maximum limit (256MB)
It's fired on this part of the KonvaJS library:
setHeight: function(t) {
this.height = this._canvas.height = t * this.pixelRatio, this._canvas.style.height = t + "px";
var e = this.pixelRatio;
this.getContext()._context.scale(e, e)
},
The line that fires the error is:
this.getContext()._context.scale(e, e)
By the way, I'm not sure if it's related, but in the mouse move event I'm running also this code to fix an issue with the scale property:
var newPos = stage.getPointerPosition();
var stageTransform = stage.getAbsoluteTransform().copy();
newPos = stageTransform.invert().point(newPos);
Any ideas of what can be the problem?
Thanks in advance!

Need help in using turtle module

So I'm writing a program using the turtle module. I have 2 questions:
I have 4 turtles. How can I make their names show up on the screen while drawing?
After I finish drawing, how can I exit one screen and open another within the same program?
I have 4 turtles. How can I make their names show up on the screen
while drawing?
Sure, here's a crude example:
from random import choice
from turtle import Turtle, Screen
NAMES = ['Donnie', 'Raph', 'Mickey', 'Leo']
SPEEDS = ["slowest", "slow", "normal", "fast", "fastest"]
FONT = ("Arial", 12, "normal")
MAGNIFICATION = 5
STAMP_SIZE = 20
MAXIMUM_SPEED = 10
LINE_OFFSET = 50
screen = Screen()
WINDOW_WIDTH = screen.window_width()
START, FINISH = LINE_OFFSET - WINDOW_WIDTH//2, WINDOW_WIDTH//2 - (LINE_OFFSET + MAXIMUM_SPEED)
turtles = {name: Turtle(shape='turtle') for name in NAMES}
for offset, turtle in enumerate(turtles.values(), start=-len(NAMES)//2):
turtle.turtlesize(MAGNIFICATION)
turtle.color("black", "white")
turtle.penup()
turtle.goto(START, offset * MAGNIFICATION * STAMP_SIZE)
turtle.speed(choice(SPEEDS))
turtle.write("", font=FONT) # dummy write for 1st undo
winner = False
while not winner:
for name, turtle in turtles.items():
turtle.undo() # unwrite name
turtle.forward(turtle.speed() + 1)
turtle.write(name, font=FONT) # rewrite name
if turtle.xcor() >= FINISH:
winner = True
break
screen.exitonclick()
To do better with respect to text centering and eliminating flicker, we would need one or more extra invisible turtles to just handle the text. However, when the turtles turn, the text won't turn with them, it'll always be horizontal.

WP7 -Live Tiles - Count Value (number in circle) - Mango

I have a function that I'm calling that basically returns a string. If the string = "OVER DUE!" I want to display an alert on the main tile (a number inside a circle). However, if the user corrects this problem I want to clear that tile and just show a normal tile with no number.
The code below does what I want it to do the 1st time it checks. So if I get an "OVER DUE!" everything works great. But if I correct it, the second tile updates but the main tile still has the number inside the circle. What do I need to do to clear the main tile back to its original state?
I would also like to clean up this code as it really is duplicated. Does anyone have any suggestions how I can write 1 function to do what I want?
if (nextDateCheck != "OVER DUE!")
{
var standardTile = new StandardTileData
{
Title = "Change your Oil",
BackgroundImage = new Uri("w7ChangeYourOil_icon_transparent.png", UriKind.Relative),
BackTitle = "Next Oil Change",
BackContent = "Your next Oil Change is: " + nextDateCheck.ToString()
};
appTile.Update(standardTile);
}
else
{
var standardTile = new StandardTileData
{
Title = "Change your Oil",
BackgroundImage = new Uri("w7ChangeYourOil_icon_transparent.png", UriKind.Relative),
Count = 1, // any number can go here, leaving this null shows NO number
BackTitle = "Next Oil Change",
BackContent = "Your next Oil Change is: " + nextDateCheck.ToString()
};
appTile.Update(standardTile);
}
The answer is quite simple really.
You need to set the Tile count back to 0 when you want to unset the number graphic on the front of the tile.
Reason being it's due to the way the original framework used to be Push Notification driven only which the new Local Tile framework still has to support.
The Title, Front Image and count are still overlays on top of the new programmatic tile options.
Hope this helps

Resources