Marketcap increase from when I bought

Viewed 43

I have the code that enters the trade if the marketcap of the cryptocurrency decreases by 3%. How would I change this so that it exits the trade when the marketcap increases/decreases by X% from the price at which it entered the trade?

change = input(3, title = "MktCap 1D percent change")/100.0     // <=== Change the value of 3 to whatever percentage you would like
rr(s, bb)=>(s - s[bb])/s
signal(s, bb)=>
    rr = rr(s, bb)
    //long = rr >= change       // <=== For a percentage increase
    long = rr <= -change        // <=== For a percentage decrease
    [long]
[long] = request.security("CRYPTOCAP:"+syminfo.basecurrency, "D", signal(close,1))

if (long and timePeriod)
    strategy.entry("Long", strategy.long)
1 Answers

If you mean market cap value change by X%:

cap = request.security("CRYPTOCAP:" + syminfo.basecurrency, "D", close) // store market cap first for more flexibility  

capChange(base, newVal) => na(base) ? 0 : (newVal - base)/base  

var float lastCap = na // "var" declaration to keep the value of lastCap over bars
...
// your entry logic...
if true  
    lastCap := cap // we enter the trade with this cap
    strategy.entry("Long", ...)
...  
if strategy.opentrades > 0 and math.abs(capChange(lastCap, cap)) >= change
    lastCap := na
    strategy.close("Long") // "Long" is the ID you chose for your entry trade that you want to close
...

You should store your cap value separately so that you can use it for "go long" / "go short" or "exit" evaluations. You can include further checks in your conditional if you want to close short/long which one etc. it depends on your needs. It's just a simple solution.

If you mean entry price change by X%:

...
if strategy.opentrades > 0
    posPrice = strategy.opentrades.entry_price(strategy.opentrades - 1)
    if math.abs(close - posPrice) / posPrice >= change
        strategy.close("Long") // needs to match entry ID
...

Related