diff --git a/.vscode/jsconfig.json b/.vscode/jsconfig.json new file mode 100644 index 0000000..e9441a4 --- /dev/null +++ b/.vscode/jsconfig.json @@ -0,0 +1,8 @@ +{ + "compilerOptions": { + "target": "esnext", + "lib": [ + "esnext" + ] + } +} \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..8f21c36 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,54 @@ +{ + "configurations": [ + { + "type": "pwa-msedge", + "name": "Launch Microsoft Edge", + "request": "launch", + "runtimeArgs": [ + "--remote-debugging-port=9222" + ], + "url": "c:\\Users\\Aek ProTrader\\.vscode\\extensions\\ms-edgedevtools.vscode-edge-devtools-2.0.0\\out\\startpage\\index.html", // Provide your project's url to finish configuring + "presentation": { + "hidden": true + } + }, + { + "type": "pwa-msedge", + "name": "Launch Microsoft Edge in headless mode", + "request": "launch", + "runtimeArgs": [ + "--headless", + "--remote-debugging-port=9222" + ], + "url": "c:\\Users\\Aek ProTrader\\.vscode\\extensions\\ms-edgedevtools.vscode-edge-devtools-2.0.0\\out\\startpage\\index.html", // Provide your project's url to finish configuring + "presentation": { + "hidden": true + } + }, + { + "type": "vscode-edge-devtools.debug", + "name": "Open Edge DevTools", + "request": "attach", + "url": "c:\\Users\\Aek ProTrader\\.vscode\\extensions\\ms-edgedevtools.vscode-edge-devtools-2.0.0\\out\\startpage\\index.html", // Provide your project's url to finish configuring + "presentation": { + "hidden": true + } + } + ], + "compounds": [ + { + "name": "Launch Edge Headless and attach DevTools", + "configurations": [ + "Launch Microsoft Edge in headless mode", + "Open Edge DevTools" + ] + }, + { + "name": "Launch Edge and attach DevTools", + "configurations": [ + "Launch Microsoft Edge", + "Open Edge DevTools" + ] + } + ] +} \ No newline at end of file diff --git a/.vscode/main.js b/.vscode/main.js new file mode 100644 index 0000000..8f33062 --- /dev/null +++ b/.vscode/main.js @@ -0,0 +1,12 @@ +/// +/// +// @ts-check +// API: https://code.visualstudio.com/api/references/vscode-api + +function activate(_context) { + window.showInformationMessage('Hello, Welcome to the Project AI!'); +} + +function deactivate() {} + +module.exports = { activate, deactivate } diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..625b81c --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "jupyter.jupyterServerType": "local" +} \ No newline at end of file diff --git a/Halo Strategy.py b/Halo Strategy.py new file mode 100644 index 0000000..05d082e --- /dev/null +++ b/Halo Strategy.py @@ -0,0 +1,74 @@ +import streamlit as st # web development +import numpy as np # np mean, np random +import pandas as pd # read csv, df manipulation +import time # to simulate a real time data, time loop +import plotly.express as px # interactive charts + + +# read csv from a github repo +df = pd.read_csv("https://raw.githubusercontent.com/Lexie88rus/bank-marketing-analysis/master/bank.csv") + + +st.set_page_config( + page_title = 'Real-Time Trading Strategy Dashboard', + page_icon = '✅', + layout = 'wide' +) + +# dashboard title + +st.title("Real-Time / Live Data Science Dashboard") + +# top-level filters + +job_filter = st.selectbox("Select the Job", pd.unique(df['job'])) + + +# creating a single-element container. +placeholder = st.empty() + +# dataframe filter + +df = df[df['job']==job_filter] + +# near real-time / live feed simulation + +for seconds in range(200): +#while True: + + df['age_new'] = df['age'] * np.random.choice(range(1,5)) + df['balance_new'] = df['balance'] * np.random.choice(range(1,5)) + + # creating KPIs + avg_age = np.mean(df['age_new']) + + count_married = int(df[(df["marital"]=='married')]['marital'].count() + np.random.choice(range(1,30))) + + balance = np.mean(df['balance_new']) + + with placeholder.container(): + # create three columns + kpi1, kpi2, kpi3 = st.columns(3) + + # fill in those three columns with respective metrics or KPIs + kpi1.metric(label="Age ⏳", value=round(avg_age), delta= round(avg_age) - 10) + kpi2.metric(label="Married Count 💍", value= int(count_married), delta= - 10 + count_married) + kpi3.metric(label="A/C Balance $", value= f"$ {round(balance,2)} ", delta= - round(balance/count_married) * 100) + + # create two columns for charts + + fig_col1, fig_col2 = st.columns(2) + with fig_col1: + st.markdown("### First Chart") + fig = px.density_heatmap(data_frame=df, y = 'age_new', x = 'marital') + st.write(fig) + with fig_col2: + st.markdown("### Second Chart") + fig2 = px.histogram(data_frame = df, x = 'age_new') + st.write(fig2) + st.markdown("### Detailed Data View") + st.dataframe(df) + time.sleep(1) + #placeholder.empty() + + diff --git a/Tradingview/Indicator/Indicator - Wedge and Flag Finder Multi - zigzag.pine b/Tradingview/Indicator/Indicator - Wedge and Flag Finder Multi - zigzag.pine new file mode 100644 index 0000000..f19c10a --- /dev/null +++ b/Tradingview/Indicator/Indicator - Wedge and Flag Finder Multi - zigzag.pine @@ -0,0 +1,308 @@ +// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ +// © HeWhoMustNotBeNamed + +// __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __ +// / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / | +// $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ | +// $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ | +// $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ | +// $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ | +// $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ | +// $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ | +// $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/ +// +// +// +//@version=5 +indicator("Wedge and Flag Finder (Multi - zigzag)", max_lines_count=500, max_labels_count=500, overlay=true, max_bars_back=2000) +import HeWhoMustNotBeNamed/zigzag/14 as zg +import HeWhoMustNotBeNamed/enhanced_ta/14 as eta +import HeWhoMustNotBeNamed/arrayutils/17 as pa + +wedgeSize = input.int(5, 'Wedge Length', options=[5,6], group='Generic', + tooltip='Defines how many pivots a wedge should comply. Options are 5 and 6 with 5 being default') +theme = input.string('Dark', title='Theme', options=['Light', 'Dark'], group='Generic', + tooltip='Chart theme settings. Line and label colors are generted based on the theme settings. If dark theme is selected, '+ + 'lighter colors are used and if light theme is selected, darker colors are used.') +avoidOverlap = input.bool(true, 'Suppress Overlap', group='Generic', + tooltip='Avoids plotting wedge if there is an existing wedge at starting point. This does not avoid nesting wedges (Wedge within wedge)') +drawZigzag = input.bool(true, 'Draw Zigzag', group='Generic', tooltip='Draw zigzag lines and mark pivots within wedge') + +showZigZag1 = input.bool(true, title='L1', group='Zigzag', inline='z1') +zigzag1Length = input.int(5, step=5, minval=3, title='', group='Zigzag', inline='z1') + +showZigZag2 = input.bool(true, title='L2', group='Zigzag', inline='z1') +zigzag2Length = input.int(8, step=5, minval=3, title='', group='Zigzag', inline='z1') + +showZigZag3 = input.bool(true, title='L3', group='Zigzag', inline='z2') +zigzag3Length = input.int(13, step=5, minval=3, title='', group='Zigzag', inline='z2') + +showZigZag4 = input.bool(true, title='L4', group='Zigzag', inline='z2') +zigzag4Length = input.int(21, step=5, minval=3, title='', group='Zigzag', inline='z2') + +applyAngleDiff = input.bool(false, 'Angle Difference', inline='ad', group='Angles') +minAngleDiff = input.int(5, '', minval=0, maxval=10, inline='ad', step=5, group='Angles') +maxAngleDiff = input.int(20, '', minval=10, maxval=90, inline='ad', step=5, group='Angles', tooltip='Show patterns where angle between trend lines falls under the selected range') + +applyAngleLimit = input.bool(false, 'Angle Range    ', inline='ar', group='Angles') +minAngleRange = input.int(10, '', minval=0, maxval=20, inline='ar', step=5, group='Angles') +maxAngleRange = input.int(60, '', minval=20, maxval=90, inline='ar', step=5, group='Angles', tooltip='Show patterns where at least one of the trend line is within the given angle range') + +var themeColors = theme=="Dark"? array.from( + color.rgb(251, 244, 109), + color.rgb(141, 186, 81), + color.rgb(74, 159, 245), + color.rgb(255, 153, 140), + color.rgb(255, 149, 0), + color.rgb(0, 234, 211), + color.rgb(167, 153, 183), + color.rgb(255, 210, 113), + color.rgb(119, 217, 112), + color.rgb(95, 129, 228), + color.rgb(235, 146, 190), + color.rgb(198, 139, 89), + color.rgb(200, 149, 149), + color.rgb(196, 182, 182), + color.rgb(255, 190, 15), + color.rgb(192, 226, 24), + color.rgb(153, 140, 235), + color.rgb(206, 31, 107), + color.rgb(251, 54, 64), + color.rgb(194, 255, 217), + color.rgb(255, 219, 197), + color.rgb(121, 180, 183) + ) : array.from( + color.rgb(61, 86, 178), + color.rgb(57, 163, 136), + color.rgb(250, 30, 14), + color.rgb(169, 51, 58), + color.rgb(225, 87, 138), + color.rgb(62, 124, 23), + color.rgb(244, 164, 66), + color.rgb(134, 72, 121), + color.rgb(113, 159, 176), + color.rgb(170, 46, 230), + color.rgb(161, 37, 104), + color.rgb(189, 32, 0), + color.rgb(16, 86, 82), + color.rgb(200, 92, 92), + color.rgb(63, 51, 81), + color.rgb(114, 106, 149), + color.rgb(171, 109, 35), + color.rgb(247, 136, 18), + color.rgb(51, 71, 86), + color.rgb(12, 123, 147), + color.rgb(195, 43, 173) + ) + + +maxPatternsReference = 10 + +var aBarArray = array.new_int() +var bBarArray = array.new_int() +var cBarArray = array.new_int() +var dBarArray = array.new_int() +var eBarArray = array.new_int() +var fBarArray = array.new_int() +var xBarArray = array.new_int() + +f_angle(a, b, loopback) => + rad2degree = 180 / math.pi + ang = rad2degree * math.atan((a - b)/(2*math.sum(ta.tr, loopback+1)/(loopback+1))) + ang + + +add_new_wedge(a,b,c,d,e,f,aBar,bBar,cBar,dBar,eBar,fBar,l1Angle, l2Angle, zgColor, wedgeSize=5)=> + dir = a>b? 1: -1 + + pa.unshift(fBarArray, fBar, maxPatternsReference) + pa.unshift(aBarArray, aBar, maxPatternsReference) + pa.unshift(bBarArray, bBar, maxPatternsReference) + pa.unshift(cBarArray, cBar, maxPatternsReference) + pa.unshift(dBarArray, dBar, maxPatternsReference) + pa.unshift(eBarArray, eBar, maxPatternsReference) + + if(drawZigzag) + ab = line.new(bBar, b, aBar, a) + bc = line.new(cBar, c, bBar, b) + cd = line.new(dBar, d, cBar, c) + de = line.new(eBar, e, dBar, d) + + aLbl = label.new(aBar, a, '5', style=label.style_none, yloc=dir>0?yloc.abovebar:yloc.belowbar, textcolor=zgColor) + bLbl = label.new(bBar, b, '4', style=label.style_none, yloc=dir<0?yloc.abovebar:yloc.belowbar, textcolor=zgColor) + cLbl = label.new(cBar, c, '3', style=label.style_none, yloc=dir>0?yloc.abovebar:yloc.belowbar, textcolor=zgColor) + dLbl = label.new(dBar, d, '2', style=label.style_none, yloc=dir<0?yloc.abovebar:yloc.belowbar, textcolor=zgColor) + eLbl = label.new(eBar, e, '1', style=label.style_none, yloc=dir>0?yloc.abovebar:yloc.belowbar, textcolor=zgColor) + if(wedgeSize == 6) + ef = line.new(fBar, f, eBar, e) + fLbl = label.new(fBar, f, '0', style=label.style_none, yloc=dir<0?yloc.abovebar:yloc.belowbar, textcolor=zgColor) + + +wedgeLine(l1StartX, l1StartY, l1EndX, l1EndY, l2StartX, l2StartY, l2EndX, l2EndY, zgColor)=> + l1t = line.new(l1StartX, l1StartY, l1EndX, l1EndY, color=zgColor, extend=extend.both) + l2t = line.new(l2StartX, l2StartY, l2EndX, l2EndY, color=zgColor, extend=extend.both) + + startBar = math.min(l2StartX, l1StartX) + endBar = l1EndX + l1Start = line.get_price(l1t, startBar) + l1End = line.get_price(l1t, endBar) + l2Start = line.get_price(l2t,startBar) + l2End = line.get_price(l2t, endBar) + + line.set_extend(l1t, extend.none) + line.set_extend(l2t, extend.none) + line.set_x1(l1t, startBar) + line.set_y1(l1t, l1Start) + line.set_x2(l1t, endBar) + line.set_y2(l1t, l1End) + + line.set_x1(l2t, startBar) + line.set_y1(l2t, l2Start) + line.set_x2(l2t, endBar) + line.set_y2(l2t, l2End) + + l1Angle = f_angle(l1End, l1Start, endBar-startBar) + l2Angle = f_angle(l2End, l2Start, endBar-startBar) + + l1Diff = math.abs(l1Start-l1End) + l2Diff = math.abs(l2Start-l2End) + + [l1t, l2t, l1Angle, l2Angle, l1Diff, l2Diff] + +find_wedge(a,b,c,d,e,f,aBar,bBar,cBar,dBar,eBar,fBar,zigzagpivots, zigzagpivotbars, fIndex, wedgeSize=6)=> + existingPattern = false + lastPivot = wedgeSize == 6? f : e + lastPivotBar = wedgeSize == 6? fBar : eBar + llastPivot = wedgeSize == 6? e : d + for i=0 to array.size(aBarArray)==0? na: array.size(aBarArray)-1 + commonPivots = (array.get(aBarArray, i) == aBar ? 1 : 0) + + (array.get(bBarArray, i) == bBar ? 1 : 0) + + (array.get(cBarArray, i) == cBar ? 1 : 0) + + (array.get(dBarArray, i) == dBar ? 1 : 0) + + (array.get(eBarArray, i) == eBar ? 1 : 0) + + (wedgeSize == 6 and array.get(fBarArray, i) == fBar ? 1 : 0) + + if(commonPivots >=2) or (avoidOverlap and lastPivotBar < array.get(aBarArray,i) and lastPivotBar > array.get(fBarArray, i)) + existingPattern := true + break + + if(not existingPattern) + aRatio = math.abs(a-b)/math.abs(b-c) + bRatio = math.abs(b-c)/math.abs(c-d) + cRatio = math.abs(c-d)/math.abs(d-e) + dRatio = math.abs(d-e)/math.abs(e-f) + + zgColor = array.pop(themeColors) + [l1t, l2t, l1Angle, l2Angle, l1Diff, l2Diff] = wedgeLine(eBar, e, aBar, a, wedgeSize == 6?fBar:dBar, wedgeSize == 6?f:d, bBar, b, zgColor) + + isType1Wedge = aRatio >=1 and bRatio < 1 and cRatio >= 1 and (dRatio < 1 or wedgeSize==5) and l1Diff < l2Diff + isType2Wedge = aRatio <1 and bRatio >= 1 and cRatio < 1 and (dRatio >=1 or wedgeSize==5) and l1Diff > l2Diff + + angleDiff = math.abs(l1Angle-l2Angle) + angleDiffInRange = (angleDiff >= minAngleDiff and angleDiff <= maxAngleDiff) or not applyAngleDiff + angleInRange = (math.max(math.abs(l1Angle), math.abs(l2Angle)) >= minAngleRange and math.min(math.abs(l1Angle), math.abs(l2Angle)) <= maxAngleRange) or not applyAngleLimit + isWedge = (isType1Wedge or isType2Wedge) and angleDiffInRange and angleInRange + + if(isWedge) + for i = aBar to lastPivotBar + l = low[bar_index-i] + h = high[bar_index-i] + l1Price = line.get_price(l1t, i) + l2Price = line.get_price(l2t, i) + if(h < math.min(l1Price, l2Price) or l > math.max(l1Price, l2Price)) + isWedge := false + break + if(i == cBar and (l1Price > h or l1Price < l)) + isWedge := false + break + if(i == dBar and (l2Price > h or l2Price < l)) + isWedge := false + break + + if isWedge + wedgeType = isType1Wedge? 1 : 2 + add_new_wedge(a,b,c,d,e,f,aBar,bBar,cBar,dBar,eBar,fBar,l1Angle, l2Angle, zgColor, wedgeSize) + length = array.size(zigzagpivots) + xIndexes = pa.get_trend_series(zigzagpivots, fIndex, length) + isFlag = false + for i=array.size(xIndexes)-1 to 0 + xIndex = array.get(xIndexes, i) + x = array.get(zigzagpivots, xIndex) + xBar = array.get(zigzagpivotbars, xIndex) + + flagRatio = math.abs(lastPivot-line.get_price(wedgeSize == 6?l1t:l2t, lastPivotBar))/math.abs(x-lastPivot) + + isFlag := flagRatio < 0.618 and (lastPivot-x)/math.abs(lastPivot-x) == (lastPivot-(wedgeSize == 6?b:a))/math.abs(lastPivot-(wedgeSize == 6?b:a)) + if(isFlag) + lFlag = line.new(xBar, x, lastPivotBar, lastPivot, color=zgColor, extend=extend.none) + dir = x > lastPivot? 1 : -1 + label.new(xBar, x, 'Flag', style=dir>0?label.style_label_down:label.style_label_up, yloc=yloc.price, color=zgColor, textcolor=color.black) + break + if(not isFlag) + dir = lastPivot > llastPivot? 1 : -1 + label.new(fBar, f, 'Wedge', style=dir>0?label.style_label_down:label.style_label_up, yloc=yloc.price, color=zgColor, textcolor=color.black) + + alert('New '+(isFlag?'Flag':'Wedge')+' pattern found') + array.unshift(themeColors, zgColor) + true + else + line.delete(l1t) + line.delete(l2t) + array.push(themeColors, zgColor) + false + +scan_patterns(startIndex, newPivot, zigzagpivots, zigzagpivotbars, zigzagpivotratios, zigzagpivotdirs, lastABar)=> + length = array.size(zigzagpivots) + numberOfPivots=5 + newLastABar = lastABar + if(length >= startIndex+numberOfPivots+1 and newPivot) + a = array.get(zigzagpivots, startIndex) + aBar = array.get(zigzagpivotbars, startIndex) + aIndex = startIndex + lastDir = array.get(zigzagpivotdirs, startIndex) + if(aBar!=lastABar) + newLastABar := aBar + b = array.get(zigzagpivots, startIndex+1) + bBar = array.get(zigzagpivotbars, startIndex+1) + c = array.get(zigzagpivots, startIndex+2) + cBar = array.get(zigzagpivotbars, startIndex+2) + d = array.get(zigzagpivots, startIndex+3) + dBar = array.get(zigzagpivotbars, startIndex+3) + e = array.get(zigzagpivots, startIndex+4) + eBar = array.get(zigzagpivotbars, startIndex+4) + f = e + fBar = eBar + if(wedgeSize == 6) + f := array.get(zigzagpivots, startIndex+5) + fBar := array.get(zigzagpivotbars, startIndex+5) + find_wedge(a,b,c,d,e,f,aBar,bBar,cBar,dBar,eBar,fBar,zigzagpivots, zigzagpivotbars, startIndex+wedgeSize-1,wedgeSize) + newLastABar + +startIndex = 0 +if(showZigZag1) + [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, _, _, _, _, _, newPivot, doublePivot] = zg.czigzag(zigzag1Length) + + var lastABar = 0 + lastABar := scan_patterns(startIndex+1, doublePivot, zigzagpivots, zigzagpivotbars, zigzagpivotratios, zigzagpivotdirs, lastABar) + lastABar := scan_patterns(startIndex, newPivot, zigzagpivots, zigzagpivotbars, zigzagpivotratios, zigzagpivotdirs, lastABar) + +if(showZigZag2) + [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, _, _, _, _, _, newPivot, doublePivot] = zg.czigzag(zigzag2Length) + + var lastABar = 0 + lastABar := scan_patterns(startIndex+1, doublePivot, zigzagpivots, zigzagpivotbars, zigzagpivotratios, zigzagpivotdirs, lastABar) + lastABar := scan_patterns(startIndex, newPivot, zigzagpivots, zigzagpivotbars, zigzagpivotratios, zigzagpivotdirs, lastABar) + +if(showZigZag3) + [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, _, _, _, _, _, newPivot, doublePivot] = zg.czigzag(zigzag3Length) + + var lastABar = 0 + lastABar := scan_patterns(startIndex+1, doublePivot, zigzagpivots, zigzagpivotbars, zigzagpivotratios, zigzagpivotdirs, lastABar) + lastABar := scan_patterns(startIndex, newPivot, zigzagpivots, zigzagpivotbars, zigzagpivotratios, zigzagpivotdirs, lastABar) + +if(showZigZag4) + [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, _, _, _, _, _, newPivot, doublePivot] = zg.czigzag(zigzag4Length) + + var lastABar = 0 + lastABar := scan_patterns(startIndex+1, doublePivot, zigzagpivots, zigzagpivotbars, zigzagpivotratios, zigzagpivotdirs, lastABar) + lastABar := scan_patterns(startIndex, newPivot, zigzagpivots, zigzagpivotbars, zigzagpivotratios, zigzagpivotdirs, lastABar) diff --git a/Tradingview/Indicator/indicator - Pivot Order Blocks.pine b/Tradingview/Indicator/indicator - Pivot Order Blocks.pine new file mode 100644 index 0000000..5e40cd2 --- /dev/null +++ b/Tradingview/Indicator/indicator - Pivot Order Blocks.pine @@ -0,0 +1,59 @@ +// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ +// © MensaTrader + +//@version=5 +indicator("Pivot Order Blocks", shorttitle="Pivot - OB", overlay=true, max_bars_back=500, max_boxes_count=250) + +//Titles +inputGroupTitle = "=== Pivots ===" +plotGroupTitle = "=== Plots ===" + + +//Inputs +leftLenH = input.int(title="Pivot High", defval=10, minval=1, inline="Pivot High", group=inputGroupTitle) +rightLenH = input.int(title="/", defval=10, minval=1, inline="Pivot High", group=inputGroupTitle) + +leftLenL = input.int(title="Pivot Low", defval=10, minval=1, inline="Pivot Low", group=inputGroupTitle) +rightLenL = input.int(title="/", defval=10, minval=1, inline="Pivot Low", group=inputGroupTitle) + +boxLength = input.int(30, title="Box Size", tooltip="Amount of candles long", group=plotGroupTitle) +bullBoxColor = input.color(color.new(#00E600,90), title="Bullish Box Color", group=plotGroupTitle, inline="1") +bearBoxColor = input.color(color.new(#FF0000,90), title="Bearish Box Color", group=plotGroupTitle, inline="1") + +ph = ta.pivothigh(leftLenH, rightLenH) +pl = ta.pivotlow(leftLenL, rightLenL) + +//Variables +var leftBull = bar_index +var rightBull = bar_index +var topBull = close +var bottomBull = close + +var leftBear = bar_index +var rightBear = bar_index +var topBear = close +var bottomBear = close + + +//Bear Box Calc +if ph + leftBear := bar_index-leftLenH + rightBear := bar_index-(leftLenH-boxLength) + topBear := close>open ? close[leftLenH] : open[leftLenH] + bottomBear := close>open ? open[leftLenH] : close[leftLenH] + +//Bull Box Calc +if pl + leftBull := bar_index-leftLenL + rightBull := bar_index-(leftLenL-boxLength) + topBull := close>open ? close[leftLenL] : open[leftLenL] + bottomBull := close>open ? open[leftLenL] : close[leftLenL] + + +if pl + bull = box.new(left=leftBull, right=rightBull, top=topBull, bottom=bottomBull, bgcolor=color.new(bullBoxColor,80), border_color=bullBoxColor) + +if ph + bear = box.new(left=leftBear, right=rightBear, top=topBear, bottom=bottomBear, bgcolor=color.new(bearBoxColor,80), border_color=bearBoxColor) + + diff --git a/Tradingview/Strategy/Strategy - Bitcoin Sniper 5X v.1.pine b/Tradingview/Strategy/Strategy - Bitcoin Sniper 5X v.1.pine new file mode 100644 index 0000000..c33bdef --- /dev/null +++ b/Tradingview/Strategy/Strategy - Bitcoin Sniper 5X v.1.pine @@ -0,0 +1,582 @@ +// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ +// © wielkieef + +//@version=4 +strategy("Bitcoin Sniper 5X v1. ", overlay = true, pyramiding=1,initial_capital = 10000, default_qty_type= strategy.percent_of_equity, default_qty_value = 100, calc_on_order_fills=false, slippage=0,commission_type=strategy.commission.percent,commission_value=0.03) + + +//SOURCE ============================================================================================================================================================================================================================================================================================================= + +src = input(open, title="  Source") + +// Indicators Inputs ======================================================================================================================================================================================================================================================================================================== + +//ADX------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +ADX_options = input("MASANAKAMURA", title="  Adx Type", options = ["CLASSIC", "MASANAKAMURA"], group="Average Directional Index") +ADX_len = input(33, title="  Adx Lenght", type=input.integer, minval = 1, group="Average Directional Index") +th = input(12, title="  Adx Treshold", type=input.integer, minval = 0, group="Average Directional Index") + +// Support and Resistance --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +SHOW_S_R = input(false, title="Show Support and Resistance levels", group="Support and Resistance") +left = input(7, title="  Left", group="Support and Resistance") +right = input(8, title="  Right", group="Support and Resistance") + +// Volume ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + +volume_f = input(1.2, title="  Volume mult.", minval = 0, step = 0.1, group="Volume") +sma_length = input(24, title="  Volume lenght", minval = 1, group="Volume") + +//SAR---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +SHOW_SAR = input(true, title="Show Parabolic SAR", group="SAR") +Sst = input (0.25, title="  Sar Start", step=0.01, minval = 0.01, group="SAR") +Sinc = input (0.2, title="  Sar Int", step=0.01, minval = 0.01, group="SAR") +Smax = input (0.1, title="  Sar Max", step=0.01, minval = 0.01, group="SAR") + +// Range Filter --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +per_ = input(8, title="  Period", minval=1, group = "Range Filter") +mult = input(1.4, title="  mult.", minval=0.1, step = 0.1, group = "Range Filter") + +//MACD---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +fast_length = input(15, title="  Fast Length", type=input.integer, group="MACD") +slow_length = input(17, title="  Slow Length", type=input.integer, group="MACD") +signal_length = input(20, title="  Signal Smoothing", type=input.integer, group="MACD") + +//RSI---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +len_3 = input(55, title="  RSI Lenght", group = "Relative Strenght Indeks") +src_3 = input(low, title="  RSI Source", group = "Relative Strenght Indeks") + +//Momentum----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +tmolength = input(3, title="  Momentum Length", group="Momentum") +smoothLength = input(21, title="  Smooth length", group="Momentum") + +//MA--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +length = input(17, title="  MA Length", minval=1, group="Fast MA" ) +matype = input(5, title="  AvgType", minval=1, maxval=5, group="Fast MA") + +//JMA-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +SHOW_JMA = input(true, title="Show Jurik Moving Average", group = "Jurik Moving Average") +inp = input(defval=low, title="  JMA Source", type=input.source, group = "Jurik Moving Average") +reso = input("", title="  JMA Resolution", type=input.resolution, group = "Jurik Moving Average") +lengths = input(14, title="  JMA Length", type=input.integer, group = "Jurik Moving Average") + +//Scalpng ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +HiLoLen = input(3, title="  Ema Scalping Lenght", minval=2, group="Ema Scalping") + +//RMI ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +RMI_len = input(33, title="  Rmi Lenght", type=input.integer, minval = 1, group="Relative Momentum Index") +mom = input(15, title="  Rmi Momentum", type=input.integer, minval = 1, group="Relative Momentum Index") +RMI_os = input(44, title="  Rmi overbought", type=input.integer, minval = 0, group="Relative Momentum Index") +RMI_ob = input(62, title="  Rmi overbought", type=input.integer, minval = 0, group="Relative Momentum Index") + +//BOLINGER BANDS ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +SHOW_BB = input(true, title="Show Bollinger Bands", group="Bolinger Bands") +bb_length = input(9, title="  Bollinger Bands Length", group="Bolinger Bands") +bb_source = input(high, title="  Bollinger Bands Source", group="Bolinger Bands") + +// ATR ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +prd = input(2, title="  PP period", group="Average True Range") +Factor = input(9, title="  ATR Factor", group="Average True Range") +Pd = input(2, title="  ATR Period", group="Average True Range") + +//TP PLOTSHAPE ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +tp_long0 = input(0.9, title="  % TP Long", type = input.float, minval = 0, step = 0.1, group="Target Point") +tp_short0 = input(0.9, title="  % TP Short", type = input.float, minval = 0, step = 0.1, group="Target Point") + +// SL PLOTSHAPE --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +sl0 = input(5.5, title="  % Stop loss", type = input.float, minval = 0, step = 0.1, group="Stop Loss") + +//INDICATORS ======================================================================================================================================================================================================================================================================================================= + +//ADX------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +calcADX(_len) => + up = change(high) + down = -change(low) + plusDM = na(up) ? na : (up > down and up > 0 ? up : 0) + minusDM = na(down) ? na : (down > up and down > 0 ? down : 0) + truerange = rma(tr, _len) + _plus = fixnan(100 * rma(plusDM, _len) / truerange) + _minus = fixnan(100 * rma(minusDM, _len) / truerange) + sum = _plus + _minus + _adx = 100 * rma(abs(_plus - _minus) / (sum == 0 ? 1 : sum), _len) + [_plus,_minus,_adx] +calcADX_Masanakamura(_len) => + SmoothedTrueRange = 0.0 + SmoothedDirectionalMovementPlus = 0.0 + SmoothedDirectionalMovementMinus = 0.0 + TrueRange = max(max(high - low, abs(high - nz(close[1]))), abs(low - nz(close[1]))) + DirectionalMovementPlus = high - nz(high[1]) > nz(low[1]) - low ? max(high - nz(high[1]), 0) : 0 + DirectionalMovementMinus = nz(low[1]) - low > high - nz(high[1]) ? max(nz(low[1]) - low, 0) : 0 + SmoothedTrueRange := nz(SmoothedTrueRange[1]) - (nz(SmoothedTrueRange[1]) /_len) + TrueRange + SmoothedDirectionalMovementPlus := nz(SmoothedDirectionalMovementPlus[1]) - (nz(SmoothedDirectionalMovementPlus[1]) / _len) + DirectionalMovementPlus + SmoothedDirectionalMovementMinus := nz(SmoothedDirectionalMovementMinus[1]) - (nz(SmoothedDirectionalMovementMinus[1]) / _len) + DirectionalMovementMinus + DIP = SmoothedDirectionalMovementPlus / SmoothedTrueRange * 100 + DIM = SmoothedDirectionalMovementMinus / SmoothedTrueRange * 100 + DX = abs(DIP-DIM) / (DIP+DIM)*100 + adx = sma(DX, _len) + [DIP,DIM,adx] +[DIPlusC,DIMinusC,ADXC] = calcADX(ADX_len) +[DIPlusM,DIMinusM,ADXM] = calcADX_Masanakamura(ADX_len) + +DIPlus = ADX_options == "CLASSIC" ? DIPlusC : DIPlusM +DIMinus = ADX_options == "CLASSIC" ? DIMinusC : DIMinusM +ADX = ADX_options == "CLASSIC" ? ADXC : ADXM +L_adx = DIPlus > DIMinus and ADX > th +S_adx = DIPlus < DIMinus and ADX > th + +//SAR------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + +SAR = sar(Sst, Sinc, Smax) +L_sar = (SAR < close) +S_sar = (SAR > close) + +// Support and Resistance --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +hih = pivothigh(high, left, right) +lol = pivotlow (low , left, right) + +top = valuewhen(hih, high[right], 0) +bot = valuewhen(lol, low [right], 0) + +RS_Long_condt = close > top +RS_Short_condt = close < bot + +L_cross = crossover(close, top) +S_cross = crossunder(close,bot) + +// Volume ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +Volume_condt = volume > sma(volume,sma_length)*volume_f + +// Range Filter ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +var bool L_RF = na, var bool S_RF = na + +Range_filter(_src, _per_, _mult)=> + var float _upward = 0.0 + var float _downward = 0.0 + wper = (_per_*2) - 1 + avrng = ema(abs(_src - _src[1]), _per_) + _smoothrng = ema(avrng, wper)*_mult + _filt = _src + _filt := _src > nz(_filt[1]) ? ((_src-_smoothrng) < nz(_filt[1]) ? nz(_filt[1]) : (_src-_smoothrng)) : ((_src+_smoothrng) > nz(_filt[1]) ? nz(_filt[1]) : (_src+_smoothrng)) + _upward := _filt > _filt[1] ? nz(_upward[1]) + 1 : _filt < _filt[1] ? 0 : nz(_upward[1]) + _downward := _filt < _filt[1] ? nz(_downward[1]) + 1 : _filt > _filt[1] ? 0 : nz(_downward[1]) + [_smoothrng,_filt,_upward,_downward] +[smoothrng, filt, upward, downward] = Range_filter(src, per_, mult) +hband = filt + smoothrng +lband = filt - smoothrng +L_RF := high > hband and upward > 0 +S_RF := low < lband and downward > 0 + +//MACD----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +fast_ma = ema(src, fast_length) +slow_ma = ema(src, slow_length) +macd = fast_ma - slow_ma +signal_ = sma(macd, signal_length) +L_macd = macd > signal_ +S_macd = macd < signal_ + +//RSI------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + +up_3 = rma(max(change(src_3), 0), len_3) +down_3 = rma(-min(change(src_3), 0), len_3) +rsi_3 = down_3 == 0 ? 100 : up_3 == 0 ? 0 : 100 - (100 / (1 + up_3 / down_3)) +L_rsi = (rsi_3 < 70) +S_rsi = (rsi_3 > 30) + +//Momentum---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +calcLength = 10 +data = 0 +for i = 1 to tmolength-1 + if close > open[i] + data := data + 1 + if close < open[i] + data := data - 1 + +EMA5 = ema(data, calcLength) +Main = ema(EMA5, smoothLength) +Signal = ema(Main, smoothLength) + +L_momentum = Main > Signal +S_momentum = Main < Signal + +//MA------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + +simplema = sma(src,length) +exponentialma = ema(src,length) +hullma = wma(2*wma(src, length/2)-wma(src, length), round(sqrt(length))) +weightedma = wma(src, length) +volweightedma = vwma(src, length) +avgval = matype==1 ? simplema : matype==2 ? exponentialma : matype==3 ? hullma : matype==4 ? weightedma : matype==5 ? volweightedma : na +MA_speed = (avgval / avgval[1] -1 ) *100 +L_s_ma = MA_speed > 0 +S_s_ma = MA_speed < 0 + +//JMA--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +rep = false +src0 = security(syminfo.tickerid, reso, inp[rep ? 0 : barstate.isrealtime ? 1 : 0])[rep ? 0 : barstate.isrealtime ? 0 : 1] +jsa = (src0 + src0[lengths]) / 2 +sig = src0 > jsa ? 1 : src0 < jsa ? -1 : 0 +L_jma = sig > 0 +S_jma = sig < 0 + +//Scalpng ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +fastEMAlength = 10 +mediumEMAlength = 120 +slowEMAlength = 500 +filterBW = false +Lookback = 12 +UseHAcandles = true +haClose = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, close) : close +haOpen = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, open) : open +haHigh = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, high) : high +haLow = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, low) : low +isRegularFractal(mode) => + ret = mode == 1 ? high[4] < high[3] and high[3] < high[2] and high[2] > high[1] and + high[1] > high[0] : mode == -1 ? + low[4] > low[3] and low[3] > low[2] and low[2] < low[1] and low[1] < low[0] : + false + ret +isBWFractal(mode) => + ret = mode == 1 ? high[4] < high[2] and high[3] <= high[2] and high[2] >= high[1] and + high[2] > high[0] : mode == -1 ? + low[4] > low[2] and low[3] >= low[2] and low[2] <= low[1] and low[2] < low[0] : + false + ret +fastEMA = ema(haClose, fastEMAlength) +mediumEMA = ema(haClose, mediumEMAlength) +slowEMA = ema(haClose, slowEMAlength) +pacC = ema(haClose, HiLoLen) +pacL = ema(haLow, HiLoLen) +pacU = ema(haHigh, HiLoLen) +TrendDirection = fastEMA > mediumEMA and pacL > mediumEMA ? 1 : + fastEMA < mediumEMA and pacU < mediumEMA ? -1 : 0 +filteredtopf = filterBW ? isRegularFractal(1) : isBWFractal(1) +filteredbotf = filterBW ? isRegularFractal(-1) : isBWFractal(-1) +valuewhen_H0 = valuewhen(filteredtopf == true, high[2], 0) +valuewhen_H1 = valuewhen(filteredtopf == true, high[2], 1) +valuewhen_H2 = valuewhen(filteredtopf == true, high[2], 2) +higherhigh = filteredtopf == false ? false : + valuewhen_H1 < valuewhen_H0 and valuewhen_H2 < valuewhen_H0 +lowerhigh = filteredtopf == false ? false : + valuewhen_H1 > valuewhen_H0 and valuewhen_H2 > valuewhen_H0 +valuewhen_L0 = valuewhen(filteredbotf == true, low[2], 0) +valuewhen_L1 = valuewhen(filteredbotf == true, low[2], 1) +valuewhen_L2 = valuewhen(filteredbotf == true, low[2], 2) +higherlow = filteredbotf == false ? false : + valuewhen_L1 < valuewhen_L0 and valuewhen_L2 < valuewhen_L0 +lowerlow = filteredbotf == false ? false : + valuewhen_L1 > valuewhen_L0 and valuewhen_L2 > valuewhen_L0 +TradeDirection = 0 +TradeDirection := nz(TradeDirection[1]) +pacExitU = haOpen < pacU and haClose > pacU and barssince(haClose pacL and haClose < pacL and barssince(haClose>pacC)<=Lookback +Buy = TrendDirection == 1 and pacExitU +Sell = TrendDirection == -1 and pacExitL +TradeDirection := TradeDirection == 1 and haClosepacC ? 0 : + TradeDirection == 0 and Buy ? 1 : + TradeDirection == 0 and Sell ? -1 : TradeDirection +L_scalp = nz(TradeDirection[1]) == 0 and TradeDirection == 1 +S_scalp = nz(TradeDirection[1]) == 0 and TradeDirection == -1 + +// RMI ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +RMI(len, m)=> + up = ema(max(close - close[m],0), len) + dn = ema(max(close[m] - close,0), len) + RMI = dn == 0 ? 0 : 100 - 100 / (1 + up / dn) + RMI +L_rmi = crossover(RMI(RMI_len, mom), RMI_os) +S_rmi = crossunder(RMI(RMI_len, mom), RMI_ob) + +//BOLINGER BANDS ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bb_use_ema = false +bb_mult = 2.0 +fast_max_len = 6 +ema_1 = ema(bb_source, bb_length) +sma_1 = sma(bb_source, bb_length) +bb_basis = bb_use_ema ? ema_1 : sma_1 +fast_max = ema(bb_source, fast_max_len) +dev = stdev(bb_source, bb_length) +bb_dev = bb_mult * dev +bb_upper = bb_basis + bb_dev +bb_lower = bb_basis - bb_dev +nLengthSlow = 16 +nLengthFast = 6 +xSMA1_hl2 = sma(hl2, nLengthFast) +xSMA2_hl2 = sma(hl2, nLengthSlow) +xSMA1_SMA2 = xSMA1_hl2 - xSMA2_hl2 +AO = xSMA1_SMA2 >= 0 ? xSMA1_SMA2 > xSMA1_SMA2[1] ? 1 : 2 : + xSMA1_SMA2 > xSMA1_SMA2[1] ? -1 : -2 +spread = bb_upper - bb_lower +sqz_filter = true +sqz_length = 120 +sqz_threshold = 50 +avgspread = sma(spread, sqz_length) +bb_squeeze = spread / avgspread * 100 +bb_offset = atr(14) * 0.5 +bb_sqz_upper = bb_upper + bb_offset +bb_sqz_lower = bb_lower - bb_offset +L_BB = crossover(fast_max, bb_basis) and close > bb_basis and abs(AO) == 1 and (not sqz_filter or bb_squeeze > sqz_threshold) +S_BB = crossunder(fast_max, bb_basis) and close < bb_basis and abs(AO) == 2 and (not sqz_filter or bb_squeeze > sqz_threshold) + +// ATR ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +float ph = pivothigh(prd, prd) +float pl = pivotlow(prd, prd) +var float center = na +float lastpp = ph ? ph : pl ? pl : na +if lastpp + if na(center) + center := lastpp + else + + center := (center * 2 + lastpp) / 3 +Up = center - (Factor * atr(Pd)) +Dn = center + (Factor * atr(Pd)) +float TUp = na +float TDown = na +Trend = 0 +TUp := close[1] > TUp[1] ? max(Up, TUp[1]) : Up +TDown := close[1] < TDown[1] ? min(Dn, TDown[1]) : Dn +Trend := close > TDown[1] ? 1: close < TUp[1]? -1: nz(Trend[1], 1) +Trailingsl = Trend == 1 ? TUp : TDown +bsignal = Trend == 1 and Trend[1] == -1 +ssignal = Trend == -1 and Trend[1] == 1 +L_ATR = Trend == 1 +S_ATR = Trend == -1 + +//STRATEGY ========================================================================================================================================================================================================================================================================================================== + +var bool longCond = na, var bool shortCond = na +var int CondIni_long = 0, var int CondIni_short = 0 +var bool _Final_longCondition = na, var bool _Final_shortCondition = na +var float last_open_longCondition = na, var float last_open_shortCondition = na +var int last_longCondition = na, var int last_shortCondition = na +var int last_Final_longCondition = na, var int last_Final_shortCondition = na +var int nLongs = na, var int nShorts = na + +L_1 = RS_Long_condt and L_adx and L_sar and L_RF and L_macd and L_rsi and L_momentum and L_s_ma and L_jma and Volume_condt +S_1 = RS_Short_condt and S_adx and S_sar and S_RF and S_macd and S_rsi and S_momentum and S_s_ma and S_jma and Volume_condt + +L_2 = L_scalp and L_adx and L_RF and L_macd and L_rsi and L_momentum +S_2 = S_scalp and S_adx and S_RF and S_macd and S_rsi and S_momentum + +L_3 = L_rmi and L_RF and L_adx and L_momentum and L_sar +S_3 = S_rmi and S_RF and S_adx and S_momentum and S_sar + +L_4 = L_BB and L_RF and L_adx and L_momentum and L_rsi and L_s_ma +S_4 = S_BB and S_RF and S_adx and S_momentum and S_rsi and S_s_ma + + +L_basic_condt = L_1 or L_2 or L_3 or L_4 +S_basic_condt = S_1 or S_2 or S_3 or S_4 + +longCond := L_basic_condt +shortCond := S_basic_condt + +CondIni_long := longCond[1] ? 1 : shortCond[1] ? -1 : nz(CondIni_long[1] ) +CondIni_short := longCond[1] ? 1 : shortCond[1] ? -1 : nz(CondIni_short[1] ) +longCondition = (longCond[1] and nz(CondIni_long[1]) == -1 ) +shortCondition = (shortCond[1] and nz(CondIni_short[1]) == 1 ) + +//POSITION PRICE----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +var float sum_long = 0.0, var float sum_short = 0.0 +var float Position_Price = 0.0 +var bool Final_long_BB = na, var bool Final_short_BB = na +var int last_long_BB = na, var int last_short_BB = na + +last_open_longCondition := longCondition or Final_long_BB[1] ? close[1] : nz(last_open_longCondition[1] ) +last_open_shortCondition := shortCondition or Final_short_BB[1] ? close[1] : nz(last_open_shortCondition[1] ) +last_longCondition := longCondition or Final_long_BB[1] ? time : nz(last_longCondition[1] ) +last_shortCondition := shortCondition or Final_short_BB[1] ? time : nz(last_shortCondition[1] ) +in_longCondition = last_longCondition > last_shortCondition +in_shortCondition = last_shortCondition > last_longCondition +last_Final_longCondition := longCondition ? time : nz(last_Final_longCondition[1] ) +last_Final_shortCondition := shortCondition ? time : nz(last_Final_shortCondition[1] ) +nLongs := nz(nLongs[1] ) +nShorts := nz(nShorts[1] ) +if longCondition or Final_long_BB + nLongs := nLongs + 1 + nShorts := 0 + sum_long := nz(last_open_longCondition) + nz(sum_long[1]) + sum_short := 0.0 +if shortCondition or Final_short_BB + nLongs := 0 + nShorts := nShorts + 1 + sum_short := nz(last_open_shortCondition)+ nz(sum_short[1]) + sum_long := 0.0 + +Position_Price := nz(Position_Price[1]) + +Position_Price := longCondition or Final_long_BB ? sum_long/nLongs : shortCondition or Final_short_BB ? sum_short/nShorts : na + +//TP--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +var bool long_tp = na, var bool short_tp = na +var int last_long_tp = na, var int last_short_tp = na +var bool Final_Long_tp = na, var bool Final_Short_tp = na +var bool Final_Long_sl0 = na, var bool Final_Short_sl0 = na +var bool Final_Long_sl = na, var bool Final_Short_sl = na +var int last_long_sl = na, var int last_short_sl = na + +tp_long = ((nLongs > 1) ? tp_long0 / nLongs : tp_long0) / 100 +tp_short = ((nShorts > 1) ? tp_short0 / nShorts : tp_short0) / 100 +long_tp := high > (fixnan(Position_Price) * (1 + tp_long)) and in_longCondition +short_tp := low < (fixnan(Position_Price) * (1 - tp_short)) and in_shortCondition +last_long_tp := long_tp ? time : nz(last_long_tp[1]) +last_short_tp := short_tp ? time : nz(last_short_tp[1]) +Final_Long_tp := (long_tp and last_longCondition > nz(last_long_tp[1]) and last_longCondition > nz(last_long_sl[1])) +Final_Short_tp := (short_tp and last_shortCondition > nz(last_short_tp[1]) and last_shortCondition > nz(last_short_sl[1])) +L_tp = iff(Final_Long_tp, fixnan(Position_Price) * (1 + tp_long) , na) +S_tp = iff(Final_Short_tp, fixnan(Position_Price) * (1 - tp_short) , na) + +//TP SIGNALS-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +tplLevel = (in_longCondition and + (last_longCondition > nz(last_long_tp[1])) and + (last_longCondition > nz(last_long_sl[1])) and not Final_Long_sl[1]) ? + (nLongs > 1) ? + (fixnan(Position_Price) * (1 + tp_long)) : (last_open_longCondition * (1 + tp_long)) : na +tpsLevel = (in_shortCondition and + (last_shortCondition > nz(last_short_tp[1])) and + (last_shortCondition > nz(last_short_sl[1])) and not Final_Short_sl[1]) ? + (nShorts > 1) ? + (fixnan(Position_Price) * (1 - tp_short)) : (last_open_shortCondition * (1 - tp_short)) : na + +//SL --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +Risk = sl0 +Percent_Capital = 100 + +sl = in_longCondition ? min(sl0,(((Risk) * 100) / (Percent_Capital * max(1, nLongs)))) : + in_shortCondition ? min(sl0,(((Risk) * 100) / (Percent_Capital * max(1, nShorts)))) : sl0 + +Normal_long_sl = ((in_longCondition and low <= ((1 - (sl / 100)) * (fixnan(Position_Price))))) +Normal_short_sl = ((in_shortCondition and high >= ((1 + (sl / 100)) * (fixnan(Position_Price))))) +last_long_sl := Normal_long_sl ? time : nz(last_long_sl[1]) +last_short_sl := Normal_short_sl ? time : nz(last_short_sl[1]) +Final_Long_sl := Normal_long_sl and last_longCondition > nz(last_long_sl[1]) and last_longCondition > nz(last_long_tp[1]) and not Final_Long_tp +Final_Short_sl := Normal_short_sl and last_shortCondition > nz(last_short_sl[1]) and last_shortCondition > nz(last_short_tp[1]) and not Final_Short_tp + +//RE-ENTRY ON TP-HIT----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +ATR_L_STOP = ssignal and in_longCondition +ATR_S_STOP = bsignal and in_shortCondition + +if Final_Long_tp or Final_Long_sl + CondIni_long := -1 + sum_long := 0.0 + nLongs := na + +if Final_Short_tp or Final_Short_sl + CondIni_short := 1 + sum_short := 0.0 + nShorts := na + +// Colors ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +ADX_COLOR = L_adx ? color.lime : S_adx ? color.red : color.orange +BAR_COLOR = L_cross ? #1b5e20 :S_cross ? color.maroon : L_adx ? color.lime : S_adx ? color.red : color.orange +barcolor (color = BAR_COLOR) + +//PLOTS============================================================================================================================================================================================================================================================================================================== + + +plot(SHOW_JMA ? bb_basis : na , title="Jurik Moving Average", color=ADX_COLOR, transp=10, linewidth=2) + +h_BB = plot(SHOW_BB ? bb_upper : na, title="Upper Bollinger Band", color = #009688, linewidth = 2 ) +l_BB = plot(SHOW_BB ? bb_lower : na, title="Lower Bollinger Band", color = #f06292, linewidth = 2 ) +fill(h_BB, l_BB, title="Bollinger Band Background", color = in_longCondition ? #009688 : #f06292, transp = 95 ) + +plot(SHOW_SAR ? SAR : na, title="SAR", style=plot.style_circles, color=ADX_COLOR ) + +plot(L_tp, title="TP_L", style = plot.style_circles, color = color.fuchsia, linewidth = 7 ) +plot(S_tp, title="TP_S", style = plot.style_circles, color = color.fuchsia, linewidth = 7 ) + +res = plot(SHOW_S_R ? top : na, title="Reistance Level", style = plot.style_cross, offset=-left, color=top != top[1] ? na : color.green, linewidth = 1 ) +sup = plot(SHOW_S_R ? bot : na, title="Support Level", style = plot.style_cross, offset=-left, color=bot != bot[1] ? na : color.red, linewidth = 1 ) + +//Price plots ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + +plot((nLongs > 1) or (nShorts > 1) ? Position_Price : na, title = "Price", color = in_longCondition ? color.aqua : color.orange, linewidth = 2, style = plot.style_cross) +plot(tplLevel, title="Long TP ", style = plot.style_cross, color=color.fuchsia, linewidth = 1 ) +plot(tpsLevel, title="Short TP ", style = plot.style_cross, color=color.fuchsia, linewidth = 1 ) + +//PLOTSHAPES---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +plotshape(Final_Long_tp, title="TP Long Signal", style = shape.flag, location=location.abovebar, color=color.red, size=size.small , textcolor=color.red, transp = 0 ) +plotshape(Final_Short_tp, title="TP Short Signal", style = shape.flag, location=location.belowbar, color=color.green, size=size.small , textcolor=color.green, transp = 0 ) + +plotshape(longCondition, title="Long", style=shape.triangleup, location=location.belowbar, color=color.blue, size=size.tiny , transp = 0 ) +plotshape(shortCondition, title="Short", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.tiny , transp = 0 ) + +//BACKTESTING inputs -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +ACT_BT = input(true, title="Backtest", type = input.bool, group= "BACKTEST") +testStartYear = input(1997, title="start year", minval = 1997, maxval = 3000, group= "BACKTEST") +testStartMonth = input(06, title="start month", minval = 1, maxval = 12, group= "BACKTEST") +testStartDay = input(01, title="start day", minval = 1, maxval = 31, group= "BACKTEST") +testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0) +testStopYear = input(3333, title="stop year", minval=1980, maxval = 2222, group= "BACKTEST") +testStopMonth = input(12, title="stop month", minval=1, maxval=12, group= "BACKTEST") +testStopDay = input(31, title="stop day", minval=1, maxval=31, group= "BACKTEST") +testPeriodStop = timestamp(testStopYear, testStopMonth, testStopDay, 0, 0) +testPeriod = time >= testPeriodStart and time <= testPeriodStop ? true : false + +// Backtest ================================================================================================================================================================================================================================================================================================================================== + +if L_basic_condt + strategy.entry ("L", strategy.long , when = ACT_BT and testPeriod) +if S_basic_condt + strategy.entry ("S", strategy.short, when = ACT_BT and testPeriod) + + +strategy.exit("TP_L", "L", profit = (abs((last_open_longCondition * (1 + tp_long)) - last_open_longCondition) / syminfo.mintick), limit = nLongs >= 1 ? strategy.position_avg_price * (1 + tp_long) : na, loss = (abs((last_open_longCondition*(1-(sl/100)))-last_open_longCondition)/syminfo.mintick)) + +strategy.exit("TP_S", "S", profit = (abs((last_open_shortCondition * (1 - tp_short)) - last_open_shortCondition) / syminfo.mintick), limit = nShorts >= 1 ? strategy.position_avg_price*(1-(tp_short)) : na, loss = (abs((last_open_shortCondition*(1+(sl/100)))-last_open_shortCondition)/syminfo.mintick)) + +strategy.close_all( when = ATR_L_STOP or ATR_S_STOP) + + + +//Tips: + +//USDT ADRESS (BSC): +//0xc7c64d959e77bac7a402d102424da5acc23d908d + +//USDT ADRESS (TRC20): +//TEHPR5NgA2JXkhpwQA7GBxqjqJyFBcjJ9a + + + + + +// By wielkieef + + + + diff --git a/list tradingview strategy, indicator.txt b/list tradingview strategy, indicator.txt new file mode 100644 index 0000000..5f4ab7e --- /dev/null +++ b/list tradingview strategy, indicator.txt @@ -0,0 +1,3 @@ +strategy - Bitcoin Sniper 5X v1 +indicator - Wedge and Flag Finder Multi - zigzag +indicator - Pivot Order Blocks diff --git a/requirements.txt b/requirements.txt index 5303016..b23f17d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,5 @@ numpy pandas plotly.express streamlit +yfinnane +yahoo-finance \ No newline at end of file diff --git a/test run.ipynb b/test run.ipynb new file mode 100644 index 0000000..0a069f1 --- /dev/null +++ b/test run.ipynb @@ -0,0 +1,91 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Collecting yahoo-finance\n", + " Using cached yahoo-finance-1.4.0.tar.gz (8.9 kB)\n", + " Preparing metadata (setup.py): started\n", + " Preparing metadata (setup.py): finished with status 'done'\n", + "Requirement already satisfied: pytz in c:\\users\\aek protrader\\appdata\\local\\programs\\python\\python311\\lib\\site-packages (from yahoo-finance) (2022.1)\n", + "Collecting simplejson\n", + " Downloading simplejson-3.17.6.tar.gz (83 kB)\n", + " ---------------------------------------- 83.1/83.1 kB 1.6 MB/s eta 0:00:00\n", + " Preparing metadata (setup.py): started\n", + " Preparing metadata (setup.py): finished with status 'done'\n", + "Using legacy 'setup.py install' for yahoo-finance, since package 'wheel' is not installed.\n", + "Using legacy 'setup.py install' for simplejson, since package 'wheel' is not installed.\n", + "Installing collected packages: simplejson, yahoo-finance\n", + " Running setup.py install for simplejson: started\n", + " Running setup.py install for simplejson: finished with status 'done'\n", + " Running setup.py install for yahoo-finance: started\n", + " Running setup.py install for yahoo-finance: finished with status 'done'\n", + "Successfully installed simplejson-3.17.6 yahoo-finance-1.4.0\n" + ] + } + ], + "source": [ + "!pip install yahoo-finance" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "ename": "ModuleNotFoundError", + "evalue": "No module named 'javascript'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32me:\\Project - AI - Strategy Trading of Ultimate Final\\AI - Strategy Trading System #2\\real-time-live-streamlit-dashboard-python\\test run.ipynb Cell 2'\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[0m \u001b[39mimport\u001b[39;00m \u001b[39mjavascript\u001b[39;00m\n", + "\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'javascript'" + ] + } + ], + "source": [ + "import javascript\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "interpreter": { + "hash": "8687cd1ec2e220b3823408c44d71f8b41a0d82e4d414ed4c141c0943b4b6994c" + }, + "kernelspec": { + "display_name": "Python 3.10.2 64-bit", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.2" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +}