CINXE.COM

Concepts / Strategies

<!DOCTYPE html><html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><script> const url = window.location.href; const expectedUrl = url.replace( /^https:\/\/(?!beta)(\w+\.)?tradingview\.com/, 'https://www.tradingview.com', ); if (url !== expectedUrl) { window.location.replace(expectedUrl); } </script><meta name="astro-view-transitions-enabled" content="true"><meta name="astro-view-transitions-fallback" content="none"><link rel="icon" href="https://static.tradingview.com/static/images/favicon.ico"><link rel="icon" type="image/svg+xml" href="/pine-script-docs/favicon.svg"><title>Concepts / Strategies</title><meta name="og:title" content="Concepts / Strategies"><meta name="twitter:title" content="Concepts / Strategies"><meta name="description" content="Everything you need to know about Pine Script™."><meta name="og:description" content="Everything you need to know about Pine Script™."><meta name="twitter:description" content="Everything you need to know about Pine Script™."><meta name="keywords" content="tradingview, pine, script, indicators, strategies"><meta name="og:image" content="/pine-script-docs/meta-image.png"><meta name="twitter:image" content="/pine-script-docs/meta-image.png"><meta name="og:image:width" content="1200"><meta name="og:image:height" content="630"><meta name="og:url" content="https://www.tradingview.com/pine-script-docs/concepts/strategies/"><meta name="twitter:url" content="https://www.tradingview.com/pine-script-docs/concepts/strategies/"><meta name="og:type" content="website"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:site" content="@TradingView"><link rel="canonical" href="https://www.tradingview.com/pine-script-docs/concepts/strategies/"><link rel="sitemap" href="/pine-script-docs/sitemap-index.xml"><link rel="stylesheet" href="/pine-script-docs/_astro/index.CI8A0IeF.css"> <link rel="stylesheet" href="/pine-script-docs/_astro/index.BL2bgAvq.css"> <style>.tv-spinner{display:none;position:absolute;margin:0 auto;border:0 solid rgb(149 152 161 / 20%);border-radius:50%;border-top-color:var(--tv-spinner-color, #2962ff);border-left-color:var(--tv-spinner-color, #2962ff);animation:tv-spinner-container-rotate .9s linear infinite}.tv-spinner-shown{display:block}.tv-spinner-size-large{top:calc(50% - 32px);left:calc(50% - 32px);width:56px;height:56px;border-width:4px}@keyframes tv-spinner-container-rotate{to{transform:rotate(360deg)}}:root{--page-background-color: #fff;background-color:var(--page-background-color)}:root[data-theme=dark]{--page-background-color: #000}body{background-color:var(--page-background-color)}#redirect-link{display:flex;position:absolute;inset:0;align-items:center;justify-content:center}#spinner{display:block;position:absolute;opacity:1;transition:opacity .2s} .twitter-tweet:not(.twitter-tweet-rendered){padding:var(--tc-padding, 1em);border:1px solid var(--tc-border-color, #cfd9de)}.twitter-tweet:not(.twitter-tweet-rendered)>:first-child{margin-top:0}.twitter-tweet:not(.twitter-tweet-rendered)>:last-child{margin-bottom:0}lite-youtube{background-color:#000;position:relative;display:block;contain:content;background-position:center center;background-size:cover;cursor:pointer;max-width:720px}lite-youtube:before{content:attr(data-title);display:block;position:absolute;top:0;background-image:linear-gradient(180deg,#000000ab,#0000008a 14%,#00000026 54%,#0000000d 72%,#0000 94%);height:99px;width:100%;font-family:YouTube Noto,Roboto,Arial,Helvetica,sans-serif;color:#eee;text-shadow:0 0 2px rgba(0,0,0,.5);font-size:18px;padding:25px 20px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;box-sizing:border-box}lite-youtube:hover:before{color:#fff}lite-youtube:after{content:"";display:block;padding-bottom:56.25%}lite-youtube>iframe{width:100%;height:100%;position:absolute;top:0;left:0;border:0}lite-youtube>.lty-playbtn{display:block;width:100%;height:100%;background:no-repeat center/68px 48px;background-image:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 68 48"><path d="M66.52 7.74c-.78-2.93-2.49-5.41-5.42-6.19C55.79.13 34 0 34 0S12.21.13 6.9 1.55c-2.93.78-4.63 3.26-5.42 6.19C.06 13.05 0 24 0 24s.06 10.95 1.48 16.26c.78 2.93 2.49 5.41 5.42 6.19C12.21 47.87 34 48 34 48s21.79-.13 27.1-1.55c2.93-.78 4.64-3.26 5.42-6.19C67.94 34.95 68 24 68 24s-.06-10.95-1.48-16.26z" fill="red"/><path d="M45 24 27 14v20" fill="white"/></svg>');position:absolute;cursor:pointer;z-index:1;filter:grayscale(100%);transition:filter .1s cubic-bezier(0,0,.2,1);border:0}lite-youtube:hover>.lty-playbtn,lite-youtube .lty-playbtn:focus{filter:none}lite-youtube.lyt-activated{cursor:unset}lite-youtube.lyt-activated:before,lite-youtube.lyt-activated>.lty-playbtn{opacity:0;pointer-events:none}.lyt-visually-hidden{clip:rect(0 0 0 0);clip-path:inset(50%);height:1px;overflow:hidden;position:absolute;white-space:nowrap;width:1px}lite-youtube>iframe{all:unset!important;width:100%!important;height:100%!important;position:absolute!important;inset:0!important;border:0!important}lite-vimeo{font-size:10px;background-color:#000;position:relative;display:block;contain:content;background-position:center center;background-size:cover}lite-vimeo:after{content:"";display:block;padding-bottom:56.25%}lite-vimeo>iframe{all:unset!important;width:100%!important;height:100%!important;position:absolute!important;inset:0!important;border:0!important}lite-vimeo>.ltv-playbtn{content:"";position:absolute;inset:0;width:100%;background:transparent;outline:0;border:0;cursor:pointer}lite-vimeo>.ltv-playbtn:before{width:6.5em;height:4em;background:#172322bf;opacity:.8;border-radius:.25rem;transition:all .2s cubic-bezier(0,0,.2,1)}lite-vimeo>.ltv-playbtn:focus:before{outline:auto}lite-vimeo:hover>.ltv-playbtn:before{background-color:#00adef;background-color:var(--ltv-color, #00adef);opacity:1}lite-vimeo>.ltv-playbtn:after{border-style:solid;border-width:1em 0 1em 1.7em;border-color:transparent transparent transparent #fff}lite-vimeo>.ltv-playbtn:before,lite-vimeo>.ltv-playbtn:after{content:"";position:absolute;top:50%;left:50%;transform:translate3d(-50%,-50%,0)}lite-vimeo.ltv-activated:before,lite-vimeo.ltv-activated>.ltv-playbtn{cursor:unset;opacity:0;pointer-events:none} </style><script type="module" src="/pine-script-docs/_astro/hoisted.yX2nbPMa.js"></script></head> <body> <div id="search-content-blur" hidden></div> <script> /* eslint-disable @typescript-eslint/typedef */ window.ThemeProvider = (() => { function getCurrent() { return ( // eslint-disable-next-line no-restricted-syntax typeof localStorage !== 'undefined' && localStorage.getItem('tv-docs-theme') ); } const storedTheme = getCurrent(); const theme = storedTheme || (window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'); document.documentElement.dataset.theme = theme === 'light' ? 'light' : 'dark'; document.documentElement.classList.toggle( 'theme-dark', theme === 'dark', ); // add support for ui-lib themes document.documentElement.classList.toggle( 'sl-theme-dark', theme === 'dark', ); // add support for shoelace themes return { updatePickers(themeArg = storedTheme || 'auto') { let currentTheme = themeArg; if (currentTheme === 'unknown') { currentTheme = getCurrent() || 'auto'; } document .querySelectorAll('docs-theme-select') .forEach((picker) => { const select = picker.querySelector('select'); if (select) select.value = currentTheme; /** @type {HTMLTemplateElement | null} */ const tmpl = document.querySelector(`#theme-icons`); const newIcon = tmpl && tmpl.content.querySelector('.' + currentTheme); if (newIcon) { const oldIcon = picker.querySelector('svg.label-icon'); if (oldIcon) { oldIcon.replaceChildren( ...newIcon.cloneNode(true).childNodes, ); } } }); }, }; })(); /* eslint-enable @typescript-eslint/typedef */ </script><template id="theme-icons"><svg width="16" height="16" viewBox="0 0 28 28" class="light" data-icon="theme/sun-28"> <symbol id="ai:local:theme/sun-28"><g fill="currentColor"><path d="M14 3h1.5v5H14V3Zm0 18h1.5v5H14v-5Zm12-5.5V14h-5v1.5h5ZM8 14v1.5H3V14h5Zm15.3-7-1-1-3.6 3.6 1.1 1 3.5-3.5ZM9.5 18.7l1.1 1.1-3.5 3.5-1-1 3.4-3.6ZM22 23.3l1-1-3.6-3.6-1 1.1 3.5 3.5ZM10.3 9.6l-1.1 1-3.5-3.5 1-1 3.6 3.5Z"/><path fill-rule="evenodd" d="M19 14.5a4.5 4.5 0 1 1-9 0 4.5 4.5 0 0 1 9 0Zm-1.5 0a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" clip-rule="evenodd"/></g></symbol><use xlink:href="#ai:local:theme/sun-28"></use> </svg><svg width="16" height="16" viewBox="0 0 28 28" class="dark" data-icon="theme/moon-28"> <symbol id="ai:local:theme/moon-28"><path fill="currentColor" fill-rule="evenodd" d="M21 7.02A9.23 9.23 0 0 0 15.2 5 9.1 9.1 0 0 0 6 14c0 4.97 4.12 9 9.2 9a9.33 9.33 0 0 0 5.8-2.02A7 7 0 0 1 14.36 14 7 7 0 0 1 21 7.02Zm-3.95-.3a7.91 7.91 0 0 0-1.85-.22A7.6 7.6 0 0 0 7.5 14a7.6 7.6 0 0 0 7.7 7.5 8 8 0 0 0 1.85-.22A8.46 8.46 0 0 1 12.86 14c0-3.1 1.69-5.8 4.19-7.28Z" clip-rule="evenodd"/></symbol><use xlink:href="#ai:local:theme/moon-28"></use> </svg><svg width="16" height="16" viewBox="0 0 28 28" class="auto" data-icon="theme/system-28"> <symbol id="ai:local:theme/system-28"><path fill="currentColor" d="M8 4h1v2H8V4Zm0 9v2h1v-2H8Zm6-3V9h-2v1h2ZM3 9v1h2V9H3Zm5.5 3a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Zm4.2-6-.7-.7-1.4 1.4.7.7L12.7 6ZM5 13.7l-.7-.7 1.4-1.4.7.7L5 13.7Zm7.7-.7-.7.7-1.4-1.4.7-.7 1.4 1.4ZM4.3 6l.7-.7 1.4 1.4-.7.7L4.3 6Zm3 17 14-14 .8.7L8 23.7l-.7-.7Zm17.2-.1a3.5 3.5 0 0 1-3.4-5.9H21a4 4 0 1 0 3.5 5.9Z"/></symbol><use xlink:href="#ai:local:theme/system-28"></use> </svg></template> <div class="backdrop" data-mobile-menu-backdrop data-astro-cid-h2irkosh></div> <div class="menu-container" data-astro-cid-h2irkosh> <div class="header" data-astro-cid-h2irkosh> <div class="header-group" data-astro-cid-h2irkosh> <div id="version-select" data-astro-cid-kx7qoxgq> <label style="--sl-select-width: undefined; --sl-label-icon-size: 16px;" data-astro-cid-lmznfliq> <span class="sr-only" data-astro-cid-lmznfliq>Version</span> <select value="v6" data-has-border no-icon="true" data-astro-cid-lmznfliq> <option value="v6" selected="true" data-astro-cid-lmznfliq>Version 6</option><option value="v5" data-astro-cid-lmznfliq>Version 5</option><option value="v4" data-astro-cid-lmznfliq>Version 4</option><option value="v3" data-astro-cid-lmznfliq>Version 3</option> </select> <svg width="16" height="16" viewBox="0 0 24 24" class="icon caret" data-astro-cid-lmznfliq data-icon="theme/down-caret"> <symbol id="ai:local:theme/down-caret"><path fill="currentColor" d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></symbol><use xlink:href="#ai:local:theme/down-caret"></use> </svg> </label> </div> <docs-theme-select class="" data-astro-cid-3wpspbi7> <label style="--sl-select-width: 48px; --sl-label-icon-size: 28px;" data-astro-cid-lmznfliq> <span class="sr-only" data-astro-cid-lmznfliq>Theme</span> <svg width="28" height="28" viewBox="0 0 28 28" class="icon label-icon" data-button data-round data-astro-cid-lmznfliq data-icon="theme/system-28"> <use xlink:href="#ai:local:theme/system-28"></use> </svg> <select value="auto" data-button data-astro-cid-lmznfliq> <option value="dark" data-astro-cid-lmznfliq>&nbsp;&nbsp;Dark&nbsp;&nbsp;</option><option value="light" data-astro-cid-lmznfliq>&nbsp;&nbsp;Light&nbsp;&nbsp;</option><option value="auto" selected="true" data-astro-cid-lmznfliq>&nbsp;&nbsp;Auto&nbsp;&nbsp;</option> </select> </label> </docs-theme-select> <script> ThemeProvider.updatePickers('unknown'); </script> </div> <div class="header-group" data-astro-cid-h2irkosh> <div class="not-content" style="stroke-width:2px" data-astro-cid-pkzv2hgs> <button id="mobile-menu-back-button" title="Close menu" data-astro-cid-pkzv2hgs class="not-content stvb-base stvb-pointer stvb-gray stvb-medium stvb-primary stvb-icon"> <svg width="28" height="28" viewBox="0 0 28 28" data-astro-cid-h2irkosh data-icon="theme/arrow-back"> <symbol id="ai:local:theme/arrow-back"><g fill="none"><g clip-path="url(#a)"><path stroke="var(--arrow-fill-color, #131722)" d="m17 20-6-6 6-6"/></g><defs><clipPath id="a"><path fill="#fff" d="M28 28H0V0h28z"/></clipPath></defs></g></symbol><use xlink:href="#ai:local:theme/arrow-back"></use> </svg> </button> </div> </div> </div> <aside id="nav" class="keep-visible" style="--navbar-right-border-width: 0px" data-astro-cid-sa57sq6l> <div class="sidebar-viewport slick-scroll" data-astro-cid-sa57sq6l> <div class="sidebar" data-mobile data-astro-cid-sa57sq6l> <ul class="toc" aria-label="Docs sidebar" data-astro-cid-sa57sq6l> <li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/welcome" data-astro-cid-omxx3dey>Welcome to Pine Script™ v6</a></li><li class="item" data-astro-cid-omxx3dey><details data-astro-cid-omxx3dey><summary data-astro-cid-omxx3dey><div class="summary-link" data-astro-cid-omxx3dey>Pine Script™ primer</div><div class="caret" data-astro-cid-omxx3dey><svg width="18" height="18" viewBox="0 0 24 24" class="icon" data-astro-cid-omxx3dey data-icon="theme/right-caret"> <use xlink:href="#ai:local:theme/right-caret"></use> </svg></div></summary><ul class="children" data-astro-cid-omxx3dey><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/primer/first-steps" data-astro-cid-omxx3dey>First steps</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/primer/first-indicator" data-astro-cid-omxx3dey>First indicator</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/primer/next-steps" data-astro-cid-omxx3dey>Next steps</a></li></ul></details></li><li class="item" data-astro-cid-omxx3dey><details data-astro-cid-omxx3dey><summary data-astro-cid-omxx3dey><div class="summary-link" data-astro-cid-omxx3dey>Language</div><div class="caret" data-astro-cid-omxx3dey><svg width="18" height="18" viewBox="0 0 24 24" class="icon" data-astro-cid-omxx3dey data-icon="theme/right-caret"> <use xlink:href="#ai:local:theme/right-caret"></use> </svg></div></summary><ul class="children" data-astro-cid-omxx3dey><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/execution-model" data-astro-cid-omxx3dey>Execution model</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/time-series" data-astro-cid-omxx3dey>Time series</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/script-structure" data-astro-cid-omxx3dey>Script structure</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/identifiers" data-astro-cid-omxx3dey>Identifiers</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/operators" data-astro-cid-omxx3dey>Operators</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/variable-declarations" data-astro-cid-omxx3dey>Variable declarations</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/conditional-structures" data-astro-cid-omxx3dey>Conditional structures</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/loops" data-astro-cid-omxx3dey>Loops</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/type-system" data-astro-cid-omxx3dey>Type system</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/built-ins" data-astro-cid-omxx3dey>Built-ins</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/user-defined-functions" data-astro-cid-omxx3dey>User-defined functions</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/objects" data-astro-cid-omxx3dey>Objects</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/enums" data-astro-cid-omxx3dey>Enums</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/methods" data-astro-cid-omxx3dey>Methods</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/arrays" data-astro-cid-omxx3dey>Arrays</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/matrices" data-astro-cid-omxx3dey>Matrices</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/maps" data-astro-cid-omxx3dey>Maps</a></li></ul></details></li><li class="item" data-astro-cid-omxx3dey><details open data-is-parent data-is-on-path data-astro-cid-omxx3dey><summary data-astro-cid-omxx3dey><div class="summary-link" data-astro-cid-omxx3dey>Concepts</div><div class="caret" data-astro-cid-omxx3dey><svg width="18" height="18" viewBox="0 0 24 24" class="icon" data-astro-cid-omxx3dey data-icon="theme/right-caret"> <use xlink:href="#ai:local:theme/right-caret"></use> </svg></div></summary><ul class="children" data-astro-cid-omxx3dey><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/alerts" data-astro-cid-omxx3dey>Alerts</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/backgrounds" data-astro-cid-omxx3dey>Backgrounds</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/bar-coloring" data-astro-cid-omxx3dey>Bar coloring</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/bar-plotting" data-astro-cid-omxx3dey>Bar plotting</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/bar-states" data-astro-cid-omxx3dey>Bar states</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/chart-information" data-astro-cid-omxx3dey>Chart information</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/colors" data-astro-cid-omxx3dey>Colors</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/fills" data-astro-cid-omxx3dey>Fills</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/inputs" data-astro-cid-omxx3dey>Inputs</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/levels" data-astro-cid-omxx3dey>Levels</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/libraries" data-astro-cid-omxx3dey>Libraries</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/lines-and-boxes" data-astro-cid-omxx3dey>Lines and boxes</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/non-standard-charts-data" data-astro-cid-omxx3dey>Non-standard charts data</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/other-timeframes-and-data" data-astro-cid-omxx3dey>Other timeframes and data</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/plots" data-astro-cid-omxx3dey>Plots</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/repainting" data-astro-cid-omxx3dey>Repainting</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/sessions" data-astro-cid-omxx3dey>Sessions</a></li><li class="item" data-current data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/strategies" data-astro-cid-omxx3dey>Strategies</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/tables" data-astro-cid-omxx3dey>Tables</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/text-and-shapes" data-astro-cid-omxx3dey>Text and shapes</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/time" data-astro-cid-omxx3dey>Time</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/timeframes" data-astro-cid-omxx3dey>Timeframes</a></li></ul></details></li><li class="item" data-astro-cid-omxx3dey><details data-astro-cid-omxx3dey><summary data-astro-cid-omxx3dey><div class="summary-link" data-astro-cid-omxx3dey>Writing scripts</div><div class="caret" data-astro-cid-omxx3dey><svg width="18" height="18" viewBox="0 0 24 24" class="icon" data-astro-cid-omxx3dey data-icon="theme/right-caret"> <use xlink:href="#ai:local:theme/right-caret"></use> </svg></div></summary><ul class="children" data-astro-cid-omxx3dey><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/writing/style-guide" data-astro-cid-omxx3dey>Style guide</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/writing/debugging" data-astro-cid-omxx3dey>Debugging</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/writing/profiling-and-optimization" data-astro-cid-omxx3dey>Profiling and optimization</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/writing/publishing" data-astro-cid-omxx3dey>Publishing scripts</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/writing/limitations" data-astro-cid-omxx3dey>Limitations</a></li></ul></details></li><li class="item" data-astro-cid-omxx3dey><details data-astro-cid-omxx3dey><summary data-astro-cid-omxx3dey><div class="summary-link" data-astro-cid-omxx3dey>FAQ</div><div class="caret" data-astro-cid-omxx3dey><svg width="18" height="18" viewBox="0 0 24 24" class="icon" data-astro-cid-omxx3dey data-icon="theme/right-caret"> <use xlink:href="#ai:local:theme/right-caret"></use> </svg></div></summary><ul class="children" data-astro-cid-omxx3dey><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/faq/general" data-astro-cid-omxx3dey>General</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/faq/alerts" data-astro-cid-omxx3dey>Alerts</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/faq/data-structures" data-astro-cid-omxx3dey>Data structures</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/faq/functions" data-astro-cid-omxx3dey>Functions</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/faq/indicators" data-astro-cid-omxx3dey>Indicators</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/faq/other-data-and-timeframes" data-astro-cid-omxx3dey>Other data and timeframes</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/faq/programming" data-astro-cid-omxx3dey>Programming</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/faq/strings-and-formatting" data-astro-cid-omxx3dey>Strings and formatting</a></li></ul></details></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/error-messages" data-astro-cid-omxx3dey>Error messages</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/release-notes" data-astro-cid-omxx3dey>Release notes</a></li><li class="item" data-astro-cid-omxx3dey><details data-astro-cid-omxx3dey><summary data-astro-cid-omxx3dey><div class="summary-link" data-astro-cid-omxx3dey>Migration guides</div><div class="caret" data-astro-cid-omxx3dey><svg width="18" height="18" viewBox="0 0 24 24" class="icon" data-astro-cid-omxx3dey data-icon="theme/right-caret"> <use xlink:href="#ai:local:theme/right-caret"></use> </svg></div></summary><ul class="children" data-astro-cid-omxx3dey><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/migration-guides/to-pine-version-6" data-astro-cid-omxx3dey>To Pine Script™ version 6</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/migration-guides/to-pine-version-5" data-astro-cid-omxx3dey>To Pine Script™ version 5</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/migration-guides/to-pine-version-4" data-astro-cid-omxx3dey>To Pine Script™ version 4</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/migration-guides/to-pine-version-3" data-astro-cid-omxx3dey>To Pine Script™ version 3</a></li></ul></details></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/where-can-i-get-more-information" data-astro-cid-omxx3dey>Where can I get more information?</a></li> </ul> <div class="toc-bottom" data-astro-cid-sa57sq6l></div> </div> </div> </aside> </div> <header class="header" data-astro-cid-d74r2unp> <nav role="navigation" aria-label="Main Navigation" data-astro-cid-d74r2unp> <mobile-menu-button id="mobile-menu-button-wc" data-astro-cid-oojooh3d> <!-- Annoyingly I need to wrap this. TODO: improve this --> <div id="mobile-menu-button-header" data-astro-cid-oojooh3d> <div class="not-content" style="" data-astro-cid-pkzv2hgs> <button title="Open navigation menu" data-astro-cid-pkzv2hgs class="not-content stvb-base stvb-pointer stvb-gray stvb-medium stvb-secondary stvb-icon stvb-icon-force-color stvb-force-no-border"> <svg width="28" height="28" viewBox="0 0 24 24" data-astro-cid-oojooh3d data-icon="theme/bars"> <symbol id="ai:local:theme/bars"><path fill="currentColor" d="M3 8h18a1 1 0 1 0 0-2H3a1 1 0 0 0 0 2Zm18 8H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Zm0-5H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2Z"/></symbol><use xlink:href="#ai:local:theme/bars"></use> </svg> </button> </div> </div> </mobile-menu-button> <div data-hide-when-search data-astro-cid-d74r2unp> <div class="header-logo" data-astro-cid-tycb33lk> <a href="/pine-script-docs/" aria-label="Home button" data-astro-cid-tycb33lk> <div class="documentation-logo logo" data-astro-cid-tycb33lk><svg width="188" height="44" viewBox="0 0 188 44" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M26.9989 28.0001L18.4281 20.7531L11.3382 23.2611C10.402 23.5923 9.60771 22.5041 10.2085 21.7134L21.0877 7.39502C21.4749 6.88536 22.2346 6.86567 22.6478 7.35459L34.7627 21.6923C35.1531 22.1543 35.0472 22.8544 34.5376 23.1802L26.9989 28.0001ZM32.4978 22.1105L27.1641 25.5207L19.7195 19.2258C19.1767 18.7669 18.4312 18.6305 17.7611 18.8676L13.8245 20.2602L21.9253 9.59841L32.4978 22.1105Z" fill="currentColor"/> <path d="M33.432 28.0842L38.3592 34.7471C38.7427 35.2657 38.3724 36 37.7274 36H6.27248C5.62746 36 5.25722 35.2657 5.64074 34.7471L10.8523 27.6996C10.9484 27.5697 11.0822 27.4725 11.2356 27.4214L17.6878 25.2707C17.9285 25.1904 18.1932 25.2314 18.3984 25.3806L26.2854 31.1166C26.5445 31.3051 26.8922 31.3173 27.1639 31.1475L32.3838 27.885C32.7316 27.6677 33.1881 27.7544 33.432 28.0842Z" fill="currentColor"/> <path d="M59.56 13.96C63.016 13.96 65.536 16.456 65.536 19.696C65.536 22.936 63.016 25.432 59.56 25.432H57.376V31H53.896V13.96H59.56ZM59.512 22.168C61.096 22.168 62.152 21.088 62.152 19.696C62.152 18.304 61.096 17.224 59.512 17.224H57.376V22.168H59.512ZM70.8636 14.944C70.8636 16.096 69.9276 17.032 68.7516 17.032C67.6236 17.032 66.6636 16.096 66.6636 14.944C66.6636 13.792 67.6236 12.856 68.7516 12.856C69.9276 12.856 70.8636 13.792 70.8636 14.944ZM67.1196 31V19H70.4076V31H67.1196ZM73.0849 31V19H76.3729V20.368C76.9969 19.408 78.2449 18.736 79.8049 18.736C82.7089 18.736 84.4369 20.848 84.4369 23.968V31H81.1489V24.52C81.1489 22.792 80.4049 21.736 79.0369 21.736C77.5249 21.736 76.3729 22.84 76.3729 25.144V31H73.0849ZM86.2041 25C86.2041 21.448 88.8681 18.736 92.5161 18.736C95.6601 18.736 98.4201 20.752 98.4201 24.64C98.4201 24.928 98.4201 25.264 98.3721 25.768H89.3961C89.5881 27.376 91.0041 28.264 92.5881 28.264C94.0761 28.264 95.1561 27.568 95.6841 26.752L98.1321 28.576C97.0281 30.184 95.0841 31.264 92.5641 31.264C88.9881 31.264 86.2041 28.792 86.2041 25ZM92.4201 21.448C91.1961 21.448 89.8281 22.072 89.5161 23.536H95.1321C94.8441 22.12 93.6441 21.448 92.4201 21.448ZM104.412 28.24L107.076 26.008C107.916 27.28 109.38 28.024 110.772 28.024C112.14 28.024 113.052 27.352 113.052 26.368C113.052 25.408 112.356 24.736 110.676 24.16L109.236 23.656C106.5 22.696 105.036 21.112 105.036 18.784C105.036 15.568 107.484 13.672 110.796 13.672C112.884 13.672 114.708 14.392 116.172 16.024L113.868 18.4C113.052 17.416 111.996 16.936 110.82 16.936C109.644 16.936 108.54 17.44 108.54 18.448C108.54 19.48 109.38 19.936 111.18 20.584L112.548 21.088C115.044 22 116.604 23.584 116.604 26.152C116.58 29.2 114.156 31.288 110.628 31.288C107.916 31.288 105.636 30.112 104.412 28.24ZM129.859 27.808C128.827 29.872 126.667 31.264 124.171 31.264C120.619 31.264 117.811 28.624 117.811 25C117.811 21.376 120.619 18.736 124.171 18.736C126.667 18.736 128.827 20.128 129.859 22.192L127.003 23.728C126.523 22.624 125.491 21.808 124.171 21.808C122.443 21.808 121.123 23.152 121.123 25C121.123 26.848 122.443 28.192 124.171 28.192C125.491 28.192 126.523 27.376 127.003 26.272L129.859 27.808ZM131.482 31V19H134.77V20.92C135.178 19.744 136.402 18.856 137.746 18.856C138.082 18.856 138.442 18.88 138.85 19V22.336C138.346 22.168 137.89 22.072 137.362 22.072C135.802 22.072 134.77 23.296 134.77 25.264V31H131.482ZM144.215 14.944C144.215 16.096 143.279 17.032 142.103 17.032C140.975 17.032 140.015 16.096 140.015 14.944C140.015 13.792 140.975 12.856 142.103 12.856C143.279 12.856 144.215 13.792 144.215 14.944ZM140.471 31V19H143.759V31H140.471ZM146.436 36.016V19H149.724V20.344C150.276 19.576 151.548 18.736 153.204 18.736C156.396 18.736 158.844 21.592 158.844 25C158.844 28.408 156.396 31.264 153.204 31.264C151.548 31.264 150.276 30.424 149.724 29.656V36.016H146.436ZM155.508 25C155.508 23.128 154.284 21.736 152.484 21.736C150.684 21.736 149.46 23.128 149.46 25C149.46 26.872 150.684 28.264 152.484 28.264C154.284 28.264 155.508 26.872 155.508 25ZM168.407 30.88C167.879 31.048 167.231 31.144 166.319 31.144C163.775 31.144 161.735 29.728 161.735 26.8V21.88H159.311V19H161.735V15.664H165.023V19H168.407V21.88H165.023V26.152C165.023 27.616 165.647 28.192 167.063 28.192C167.591 28.192 168.023 28.12 168.407 27.976V30.88ZM177.626 22.648V13.96H179.978L181.874 16.888L183.746 13.96H186.122V22.648H183.698V18.184L181.874 20.968L180.026 18.136V22.648H177.626ZM171.386 22.648V16.456H169.058V13.96H176.258V16.456H173.93V22.648H171.386Z" fill="currentColor"/> </svg> </div> </a> </div> </div> <div class="flex" data-astro-cid-d74r2unp></div> <div class="flex" data-astro-cid-d74r2unp> <div class="search-container" data-astro-cid-fg37foga> <div class="search-wrapper" data-astro-cid-fg37foga> <input class="search-input" type="text" placeholder="Search docs" name="s" value="" data-astro-cid-fg37foga> <svg width="28" height="28" viewBox="0 0 28 28" class="search-button" data-astro-cid-fg37foga data-icon="theme/search"> <symbol id="ai:local:theme/search"><path fill="currentColor" fill-rule="evenodd" d="M18.5 12.5a6 6 0 1 1-12 0 6 6 0 0 1 12 0Zm-1.25 5.8a7.5 7.5 0 1 1 1.06-1.06l4.22 4.23.53.53L22 23.06l-.53-.53-4.22-4.22Z" clip-rule="evenodd"/></symbol><use xlink:href="#ai:local:theme/search"></use> </svg> <button class="search-clear" type="button" title="Reset" data-search-clear data-astro-cid-fg37foga>Clear</button> <span class="divider" data-astro-cid-fg37foga></span> <button class="search-close" type="button" title="Close" data-search-close data-astro-cid-fg37foga> <svg width="18" height="18" viewBox="0 0 18 18" data-astro-cid-fg37foga data-icon="theme/cross-18"> <use xlink:href="#ai:local:theme/cross-18"></use> </svg> </button> </div> <div id="search-results-wrapper" data-astro-cid-fg37foga> <aside id="search-results" hidden data-astro-cid-fg37foga> <!-- Don't use h1 because when built it will be used as the first heading on the page --> <div class="heading" data-astro-cid-fg37foga>Search results</div> <div id="search-results-contents" data-astro-cid-fg37foga></div> </aside> </div> </div> </div> <ul class="links" data-astro-cid-d74r2unp> </ul> <div class="flex" data-astro-cid-d74r2unp></div> <div data-hide-when-search data-astro-cid-d74r2unp> <div id="version-select" data-hideable="true" data-astro-cid-kx7qoxgq> <label style="--sl-select-width: undefined; --sl-label-icon-size: 16px;" data-astro-cid-lmznfliq> <span class="sr-only" data-astro-cid-lmznfliq>Version</span> <select value="v6" data-has-border no-icon="true" data-astro-cid-lmznfliq> <option value="v6" selected="true" data-astro-cid-lmznfliq>Version 6</option><option value="v5" data-astro-cid-lmznfliq>Version 5</option><option value="v4" data-astro-cid-lmznfliq>Version 4</option><option value="v3" data-astro-cid-lmznfliq>Version 3</option> </select> <svg width="16" height="16" viewBox="0 0 24 24" class="icon caret" data-astro-cid-lmznfliq data-icon="theme/down-caret"> <use xlink:href="#ai:local:theme/down-caret"></use> </svg> </label> </div> </div> <button id="search-button" data-astro-cid-6zeqadij> <svg width="28" height="28" viewBox="0 0 28 28" data-astro-cid-6zeqadij data-icon="theme/search"> <use xlink:href="#ai:local:theme/search"></use> </svg> </button> <script data-base-url="/pine-script-docs"> async function loadPageFind() { const base = document.currentScript.getAttribute('data-base-url'); const pageFindBundleUrl = `${base}/pagefind/`; const pagefind = await import(`${pageFindBundleUrl}pagefind.js`); await pagefind.options({ bundlePath: pageFindBundleUrl, }); window.pagefind = pagefind; } loadPageFind().catch(); </script> <docs-theme-select class="hide-with-breakpoint-568" data-astro-cid-3wpspbi7> <label style="--sl-select-width: 48px; --sl-label-icon-size: 28px;" data-astro-cid-lmznfliq> <span class="sr-only" data-astro-cid-lmznfliq>Theme</span> <svg width="28" height="28" viewBox="0 0 28 28" class="icon label-icon" data-button data-round data-astro-cid-lmznfliq data-icon="theme/system-28"> <use xlink:href="#ai:local:theme/system-28"></use> </svg> <select value="auto" data-button data-astro-cid-lmznfliq> <option value="dark" data-astro-cid-lmznfliq>&nbsp;&nbsp;Dark&nbsp;&nbsp;</option><option value="light" data-astro-cid-lmznfliq>&nbsp;&nbsp;Light&nbsp;&nbsp;</option><option value="auto" selected="true" data-astro-cid-lmznfliq>&nbsp;&nbsp;Auto&nbsp;&nbsp;</option> </select> </label> </docs-theme-select> <script> ThemeProvider.updatePickers('unknown'); </script> </nav> </header> <div id="image-lightbox" class="not-content" hidden data-astro-cid-kws7taxh> <div class="button-wrapper" data-astro-cid-kws7taxh> <div class="not-content" style="" data-astro-cid-pkzv2hgs> <button id="lightbox-close-button" title="Close image preview" data-astro-cid-pkzv2hgs class="not-content stvb-base stvb-pointer stvb-black stvb-medium stvb-secondary stvb-icon stvb-force-no-border"> <svg width="24" height="24" viewBox="0 0 18 18" data-astro-cid-kws7taxh data-icon="theme/cross-18"> <symbol id="ai:local:theme/cross-18"><g fill="none"><g clip-path="url(#a)"><path fill="currentColor" fill-rule="evenodd" d="M5.53 4.47 4.47 5.53 7.94 9l-3.47 3.47 1.06 1.06L9 10.06l3.47 3.47 1.06-1.06L10.06 9l3.47-3.47-1.06-1.06L9 7.94 5.53 4.47Z" clip-rule="evenodd"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h18v18H0z"/></clipPath></defs></g></symbol><use xlink:href="#ai:local:theme/cross-18"></use> </svg> </button> </div> </div> <img id="lightbox-image" src="" data-astro-cid-kws7taxh> </div> <div id="page-container" data-astro-cid-xgirumru> <aside id="nav" class="" style="" data-astro-cid-sa57sq6l> <div class="sidebar-viewport slick-scroll" data-astro-cid-sa57sq6l> <div class="sidebar" data-astro-cid-sa57sq6l> <ul class="toc" aria-label="Docs sidebar" data-astro-cid-sa57sq6l> <li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/welcome" data-astro-cid-omxx3dey>Welcome to Pine Script™ v6</a></li><li class="item" data-astro-cid-omxx3dey><details data-astro-cid-omxx3dey><summary data-astro-cid-omxx3dey><div class="summary-link" data-astro-cid-omxx3dey>Pine Script™ primer</div><div class="caret" data-astro-cid-omxx3dey><svg width="18" height="18" viewBox="0 0 24 24" class="icon" data-astro-cid-omxx3dey data-icon="theme/right-caret"> <symbol id="ai:local:theme/right-caret"><path fill="currentColor" d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></symbol><use xlink:href="#ai:local:theme/right-caret"></use> </svg></div></summary><ul class="children" data-astro-cid-omxx3dey><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/primer/first-steps" data-astro-cid-omxx3dey>First steps</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/primer/first-indicator" data-astro-cid-omxx3dey>First indicator</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/primer/next-steps" data-astro-cid-omxx3dey>Next steps</a></li></ul></details></li><li class="item" data-astro-cid-omxx3dey><details data-astro-cid-omxx3dey><summary data-astro-cid-omxx3dey><div class="summary-link" data-astro-cid-omxx3dey>Language</div><div class="caret" data-astro-cid-omxx3dey><svg width="18" height="18" viewBox="0 0 24 24" class="icon" data-astro-cid-omxx3dey data-icon="theme/right-caret"> <use xlink:href="#ai:local:theme/right-caret"></use> </svg></div></summary><ul class="children" data-astro-cid-omxx3dey><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/execution-model" data-astro-cid-omxx3dey>Execution model</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/time-series" data-astro-cid-omxx3dey>Time series</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/script-structure" data-astro-cid-omxx3dey>Script structure</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/identifiers" data-astro-cid-omxx3dey>Identifiers</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/operators" data-astro-cid-omxx3dey>Operators</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/variable-declarations" data-astro-cid-omxx3dey>Variable declarations</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/conditional-structures" data-astro-cid-omxx3dey>Conditional structures</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/loops" data-astro-cid-omxx3dey>Loops</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/type-system" data-astro-cid-omxx3dey>Type system</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/built-ins" data-astro-cid-omxx3dey>Built-ins</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/user-defined-functions" data-astro-cid-omxx3dey>User-defined functions</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/objects" data-astro-cid-omxx3dey>Objects</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/enums" data-astro-cid-omxx3dey>Enums</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/methods" data-astro-cid-omxx3dey>Methods</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/arrays" data-astro-cid-omxx3dey>Arrays</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/matrices" data-astro-cid-omxx3dey>Matrices</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/language/maps" data-astro-cid-omxx3dey>Maps</a></li></ul></details></li><li class="item" data-astro-cid-omxx3dey><details open data-is-parent data-is-on-path data-astro-cid-omxx3dey><summary data-astro-cid-omxx3dey><div class="summary-link" data-astro-cid-omxx3dey>Concepts</div><div class="caret" data-astro-cid-omxx3dey><svg width="18" height="18" viewBox="0 0 24 24" class="icon" data-astro-cid-omxx3dey data-icon="theme/right-caret"> <use xlink:href="#ai:local:theme/right-caret"></use> </svg></div></summary><ul class="children" data-astro-cid-omxx3dey><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/alerts" data-astro-cid-omxx3dey>Alerts</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/backgrounds" data-astro-cid-omxx3dey>Backgrounds</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/bar-coloring" data-astro-cid-omxx3dey>Bar coloring</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/bar-plotting" data-astro-cid-omxx3dey>Bar plotting</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/bar-states" data-astro-cid-omxx3dey>Bar states</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/chart-information" data-astro-cid-omxx3dey>Chart information</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/colors" data-astro-cid-omxx3dey>Colors</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/fills" data-astro-cid-omxx3dey>Fills</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/inputs" data-astro-cid-omxx3dey>Inputs</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/levels" data-astro-cid-omxx3dey>Levels</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/libraries" data-astro-cid-omxx3dey>Libraries</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/lines-and-boxes" data-astro-cid-omxx3dey>Lines and boxes</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/non-standard-charts-data" data-astro-cid-omxx3dey>Non-standard charts data</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/other-timeframes-and-data" data-astro-cid-omxx3dey>Other timeframes and data</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/plots" data-astro-cid-omxx3dey>Plots</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/repainting" data-astro-cid-omxx3dey>Repainting</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/sessions" data-astro-cid-omxx3dey>Sessions</a></li><li class="item" data-current data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/strategies" data-astro-cid-omxx3dey>Strategies</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/tables" data-astro-cid-omxx3dey>Tables</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/text-and-shapes" data-astro-cid-omxx3dey>Text and shapes</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/time" data-astro-cid-omxx3dey>Time</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/concepts/timeframes" data-astro-cid-omxx3dey>Timeframes</a></li></ul></details></li><li class="item" data-astro-cid-omxx3dey><details data-astro-cid-omxx3dey><summary data-astro-cid-omxx3dey><div class="summary-link" data-astro-cid-omxx3dey>Writing scripts</div><div class="caret" data-astro-cid-omxx3dey><svg width="18" height="18" viewBox="0 0 24 24" class="icon" data-astro-cid-omxx3dey data-icon="theme/right-caret"> <use xlink:href="#ai:local:theme/right-caret"></use> </svg></div></summary><ul class="children" data-astro-cid-omxx3dey><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/writing/style-guide" data-astro-cid-omxx3dey>Style guide</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/writing/debugging" data-astro-cid-omxx3dey>Debugging</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/writing/profiling-and-optimization" data-astro-cid-omxx3dey>Profiling and optimization</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/writing/publishing" data-astro-cid-omxx3dey>Publishing scripts</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/writing/limitations" data-astro-cid-omxx3dey>Limitations</a></li></ul></details></li><li class="item" data-astro-cid-omxx3dey><details data-astro-cid-omxx3dey><summary data-astro-cid-omxx3dey><div class="summary-link" data-astro-cid-omxx3dey>FAQ</div><div class="caret" data-astro-cid-omxx3dey><svg width="18" height="18" viewBox="0 0 24 24" class="icon" data-astro-cid-omxx3dey data-icon="theme/right-caret"> <use xlink:href="#ai:local:theme/right-caret"></use> </svg></div></summary><ul class="children" data-astro-cid-omxx3dey><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/faq/general" data-astro-cid-omxx3dey>General</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/faq/alerts" data-astro-cid-omxx3dey>Alerts</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/faq/data-structures" data-astro-cid-omxx3dey>Data structures</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/faq/functions" data-astro-cid-omxx3dey>Functions</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/faq/indicators" data-astro-cid-omxx3dey>Indicators</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/faq/other-data-and-timeframes" data-astro-cid-omxx3dey>Other data and timeframes</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/faq/programming" data-astro-cid-omxx3dey>Programming</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/faq/strings-and-formatting" data-astro-cid-omxx3dey>Strings and formatting</a></li></ul></details></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/error-messages" data-astro-cid-omxx3dey>Error messages</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/release-notes" data-astro-cid-omxx3dey>Release notes</a></li><li class="item" data-astro-cid-omxx3dey><details data-astro-cid-omxx3dey><summary data-astro-cid-omxx3dey><div class="summary-link" data-astro-cid-omxx3dey>Migration guides</div><div class="caret" data-astro-cid-omxx3dey><svg width="18" height="18" viewBox="0 0 24 24" class="icon" data-astro-cid-omxx3dey data-icon="theme/right-caret"> <use xlink:href="#ai:local:theme/right-caret"></use> </svg></div></summary><ul class="children" data-astro-cid-omxx3dey><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/migration-guides/to-pine-version-6" data-astro-cid-omxx3dey>To Pine Script™ version 6</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/migration-guides/to-pine-version-5" data-astro-cid-omxx3dey>To Pine Script™ version 5</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/migration-guides/to-pine-version-4" data-astro-cid-omxx3dey>To Pine Script™ version 4</a></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/migration-guides/to-pine-version-3" data-astro-cid-omxx3dey>To Pine Script™ version 3</a></li></ul></details></li><li class="item" data-astro-cid-omxx3dey><a class="page-link" href="/pine-script-docs/where-can-i-get-more-information" data-astro-cid-omxx3dey>Where can I get more information?</a></li> </ul> <div class="toc-bottom" data-astro-cid-sa57sq6l></div> </div> </div> </aside> <main class="main-pane" data-page-type="md" data-astro-cid-xgirumru> <a id="top" data-astro-cid-xgirumru></a> <main class="content" data-toc-shown data-astro-cid-ju3wuhkz> <div class="content-width" data-astro-cid-xgirumru> <div class="breadcrumbs" data-pagefind-ignore data-astro-cid-wlavna2o> <a href="/pine-script-docs" aria-label="Return back to the documentation home page." data-astro-cid-wlavna2o> <span data-astro-cid-wlavna2o>User Manual</span> </a> <span class="divider" data-astro-cid-wlavna2o>/</span> <a href="/pine-script-docs/concepts/alerts" data-astro-cid-wlavna2o>Concepts</a> <span class="divider" data-astro-cid-wlavna2o>/</span> <span class="current-item" data-astro-cid-wlavna2o>Strategies</span> </div> </div> <div id="slot-container" data-astro-cid-xgirumru> <h1 id="strategies" class="md-heading"><a href="#strategies">Strategies<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h1> <h2 id="introduction" class="md-heading"><a href="#introduction">Introduction<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p>Pine Script™ Strategies are specialized scripts that simulate trades across historical and realtime bars, allowing users to backtest and forward test their trading systems. Strategy scripts have many of the same capabilities as <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_indicator">indicator</a> scripts, and they provide the ability to place, modify, and cancel hypothetical orders and analyze performance results.</p> <p>When a script uses the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> function as its declaration statement, it gains access to the <code dir="auto">strategy.*</code> namespace, which features numerous functions and variables for simulating orders and retrieving essential strategy information. It also displays relevant information and simulated performance results in the dedicated <a href="/pine-script-docs/concepts/strategies/#strategy-tester">Strategy Tester</a> tab.</p> <h2 id="a-simple-strategy-example" class="md-heading"><a href="#a-simple-strategy-example">A simple strategy example<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p>The following script is a simple strategy that simulates entering a long or short position when two moving averages cross. When the <code dir="auto">fastMA</code> crosses above the <code dir="auto">slowMA</code>, it places a “buy” market order to enter a long position. When the <code dir="auto">fastMA</code> crosses below the <code dir="auto">slowMA</code>, it places a “sell” market order to enter a short position:</p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Simple strategy demo&quot;, overlay = true, margin_long = 100, margin_short = 100) //@variable The length of the `fastMA` and half the length of the `slowMA`. int lengthInput = input.int(14, &quot;Base length&quot;, 2) // Calculate two moving averages with different lengths. float fastMA = ta.sma(close, lengthInput) float slowMA = ta.sma(close, lengthInput * 2) // Place an order to enter a long position when `fastMA` crosses over `slowMA`. if ta.crossover(fastMA, slowMA) strategy.entry(&quot;buy&quot;, strategy.long) // Place an order to enter a short position when `fastMA` crosses under `slowMA`. if ta.crossunder(fastMA, slowMA) strategy.entry(&quot;sell&quot;, strategy.short) // Plot the moving averages. plot(fastMA, &quot;Fast MA&quot;, color.aqua) plot(slowMA, &quot;Slow MA&quot;, color.orange)</div> <p>Note that:</p> <ul> <li>The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> function call declares that the script is a strategy named “Simple strategy demo” that displays visuals on the main chart pane.</li> <li>The <code dir="auto">margin_long</code> and <code dir="auto">margin_short</code> arguments in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> call specify that the strategy must have 100% of a long or short trade’s amount available to allow the trade. See <a href="/pine-script-docs/concepts/strategies/#margin">this section</a> for more information.</li> <li>The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> function is the command that the script uses to create entry orders and reverse positions. The “buy” entry order closes any short position and opens a new long position. The “sell” entry order closes any long position and opens a new short position.</li> </ul> <h2 id="applying-a-strategy-to-a-chart" class="md-heading"><a href="#applying-a-strategy-to-a-chart">Applying a strategy to a chart<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p>To test a strategy, add it to the chart. Select a built-in or published strategy from the “Indicators, Metrics &amp; Strategies” menu, or write a custom strategy in the Pine Editor and click the “Add to chart” option in the top-right corner:</p> <p><img src="/pine-script-docs/_astro/Strategies-Applying-a-strategy-to-a-chart-1.N4wBY_BO_Z2vpEWq.webp" alt="image" width="1052" height="356" loading="lazy" decoding="async"></p> <p>The script plots trade markers on the main chart pane and displays simulated performance results inside the <a href="/pine-script-docs/concepts/strategies/#strategy-tester">Strategy Tester</a> tab:</p> <p><img src="/pine-script-docs/_astro/Strategies-Applying-a-strategy-to-a-chart-2.DYfs3WKI_Z1EwIMy.webp" alt="image" width="1336" height="764" loading="lazy" decoding="async"></p> <aside aria-label="Notice!" class="tv-informer not-content" style="--informer-header-color:#FF9800;--informer-back-color-light:#FFF3E0;--informer-back-color-dark:#33261A"><div class="tv-informer-icon"><svg viewBox="0 0 18 18" width="18" height="18"><path fill-rule="evenodd" d="M9 17A8 8 0 1 0 9 1a8 8 0 0 0 0 16ZM9 4c-.79 0-1.38.7-1.25 1.48l.67 4.03a.59.59 0 0 0 1.16 0l.67-4.03A1.27 1.27 0 0 0 9 4Zm0 8a1 1 0 1 0 0 2 1 1 0 0 0 0-2Z" fill="currentColor"></path></svg></div><div class="tv-informer-content"><p><span class="tv-informer-header">Notice!</span></p><p>The performance results from a strategy applied to <em>non-standard charts</em> (<a href="https://www.tradingview.com/support/solutions/43000619436">Heikin Ashi</a>, <a href="https://www.tradingview.com/support/solutions/43000502284">Renko</a>, <a href="https://www.tradingview.com/support/solutions/43000502273">Line Break</a>, <a href="https://www.tradingview.com/support/solutions/43000502272">Kagi</a>, <a href="https://www.tradingview.com/support/solutions/43000502276">Point &amp; Figure</a>, and <a href="https://www.tradingview.com/support/solutions/43000474007">Range</a>) <strong>do not</strong> reflect actual market conditions by default. The strategy uses the chart’s <strong>synthetic</strong> prices in its simulation, which do not typically represent real-world market prices, leading to unrealistic strategy results.</p><p>Therefore, we strongly recommend using <strong>standard</strong> chart types when testing strategies. Alternatively, on Heikin Ashi charts, users can simulate order fills using actual prices by enabling the <em>“Fill orders on standard OHLC”</em> option in the strategy’s <a href="https://www.tradingview.com/support/solutions/43000628599">properties</a> or including <code dir="auto">fill_orders_on_standard_ohlc = true</code> in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement.</p><p></p></div></aside> <h2 id="strategy-tester" class="md-heading"><a href="#strategy-tester">Strategy Tester<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p>The <em>Strategy Tester</em> visualizes the hypothetical performance of a strategy script and displays its properties. To use it, add a script declared with the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> function to the chart, then open the “Strategy Tester” tab. If two or more strategies are on the chart, specify which one to analyze by selecting its name in the top-left corner.</p> <p>After the selected script executes across the chart’s data, the Strategy Tester populates the following four tabs with relevant strategy information:</p> <ul> <li><a href="/pine-script-docs/concepts/strategies/#overview">Overview</a></li> <li><a href="/pine-script-docs/concepts/strategies/#performance-summary">Performance Summary</a></li> <li><a href="/pine-script-docs/concepts/strategies/#list-of-trades">List of Trades</a></li> <li><a href="/pine-script-docs/concepts/strategies/#properties">Properties</a></li> </ul> <h3 id="overview" class="md-heading"><a href="#overview">Overview<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>The <a href="https://www.tradingview.com/support/solutions/43000681733">Overview</a> tab provides a quick look into a strategy’s performance over a sequence of simulated trades. This tab displays essential performance metrics and a chart with three helpful plots:</p> <ul> <li>The <a href="https://www.tradingview.com/support/solutions/43000681735">Equity</a> baseline plot visualizes the strategy’s simulated equity across closed trades.</li> <li>The <a href="https://www.tradingview.com/support/solutions/43000681734">Drawdown</a> column plot shows how far the strategy’s equity fell below its peak across trades.</li> <li>The <a href="https://www.tradingview.com/support/solutions/43000681736">Buy &amp; hold equity</a> plot shows the equity growth of a strategy that enters a single long position and holds that position throughout the testing range.</li> </ul> <p><img src="/pine-script-docs/_astro/Strategies-Strategy-tester-Overview-1.DOd5fCK__1TlKcc.webp" alt="image" width="1336" height="760" loading="lazy" decoding="async"></p> <p>Note that:</p> <ul> <li>The chart has two separate vertical scales. The “Equity” and “Buy &amp; hold equity” plots use the scale on the left, and the “Drawdown” plot uses the scale on the right. Users can toggle the plots and choose between absolute or percentage scales using the options at the bottom.</li> <li>When a user clicks on a point in this chart, the main chart scrolls to the corresponding bar where the trade closed and displays a tooltip containing the closing time.</li> </ul> <h3 id="performance-summary" class="md-heading"><a href="#performance-summary">Performance Summary<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>The <a href="https://www.tradingview.com/support/solutions/43000681683">Performance Summary</a> tab presents an in-depth summary of a strategy’s key performance metrics, organized into separate columns. The “All” column shows performance information for all simulated trades, and the “Long” and “Short” columns show relevant metrics separately for long and short trades. This view provides more detailed insights into a strategy’s overall and directional trading performance:</p> <p><img src="/pine-script-docs/_astro/Strategies-Strategy-tester-Performance-summary-1.BWnlmBT7_Z38011.webp" alt="image" width="1336" height="768" loading="lazy" decoding="async"></p> <h3 id="list-of-trades" class="md-heading"><a href="#list-of-trades">List of Trades<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>The <a href="https://www.tradingview.com/support/solutions/43000681737">List of Trades</a> tab chronologically lists a strategy’s simulated trades. Each item in the list displays vital information about a trade, including the dates and times of entry and exit orders, the names of the orders, the order prices, and the number of contracts/shares/lots/units. In addition, each item shows the trade’s profit or loss and the strategy’s cumulative profit, run-up, and drawdown:</p> <p><img src="/pine-script-docs/_astro/Strategies-Strategy-tester-List-of-trades-1.Chdio170_1pKv1G.webp" alt="image" width="1336" height="764" loading="lazy" decoding="async"></p> <p>Note that:</p> <ul> <li>Hovering the mouse over a list item’s entry or exit information reveals a “Scroll to bar” button. Clicking that button navigates the main chart to the bar where the entry or exit occurred.</li> <li>The list shows each trade in <em>descending</em> order by default, with the latest trade at the top. Users can reverse this order by clicking the “Trade #” button above the list.</li> </ul> <h3 id="properties" class="md-heading"><a href="#properties">Properties<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>The “Properties” tab provides detailed information about a strategy’s configuration and the dataset that it executes across, organized into four collapsible sections:</p> <ul> <li>The “Date Range” section shows the range of dates that had simulated trades, and the overall available backtesting range.</li> <li>The “Symbol Info” section displays the chart’s symbol, timeframe, type, point value, currency, and tick size. It also includes the chart’s specified precision setting.</li> <li>The “Strategy Inputs” section lists the names and values of all the inputs available in the strategy’s “Settings/Inputs” tab. This section only appears if the script includes <code dir="auto">input*()</code> calls or specifies a nonzero <code dir="auto">calc_bars_count</code> argument in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement.</li> <li>The “Strategy Properties” section provides an overview of the strategy’s <a href="https://www.tradingview.com/support/solutions/43000628599-strategy-properties/">properties</a>, including the initial capital, account currency, order size, margin, pyramiding, commission, slippage, and other settings.</li> </ul> <p><img src="/pine-script-docs/_astro/Strategies-Strategy-tester-Properties-1.DEisjv-X_Z5vT3G.webp" alt="image" width="1336" height="340" loading="lazy" decoding="async"></p> <h2 id="broker-emulator" class="md-heading"><a href="#broker-emulator">Broker emulator<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p>TradingView uses a <em>broker emulator</em> to simulate trades while running a strategy script. Unlike in real-world trading, the emulator fills a strategy’s orders exclusively using available <em>chart data</em> by default. Consequently, it executes orders on historical bars <em>after a bar closes</em>. Similarly, the earliest point that it can fill orders on realtime bars is after a new price tick. For more information about this behavior, see the <a href="/pine-script-docs/language/execution-model/">Execution model</a> page.</p> <p>Because the broker emulator only uses price data from the chart by default, it makes <em>assumptions</em> about intrabar price movement when filling orders. The emulator analyzes the opening, high, low, and closing prices of chart bars to infer intrabar activity using the following logic:</p> <ul> <li>If the opening price of a bar is closer to the high than the low, the emulator assumes that the market price moved in this order: <strong>open → high → low → close</strong>.</li> <li>If the opening price of a bar is closer to the low than the high, the emulator assumes that the market price moved in this order: <strong>open → low → high → close</strong>.</li> <li>The emulator assumes <em>no gaps</em> exist between intrabars inside each chart bar, meaning it considers <em>any</em> value within a bar’s high-low range as a valid price for order execution.</li> <li>When filling <em>price-based orders</em> (all orders except <a href="/pine-script-docs/concepts/strategies/#market-orders">market orders</a>), the emulator assumes intrabars <strong>do not</strong> exist within the gap between the previous bar’s close and the current bar’s open. If the market price crosses an order’s price during the gap between two bars, the emulator fills the order at the current bar’s <em>open</em> and not at the specified price.</li> </ul> <p><img src="/pine-script-docs/_astro/Strategies-Broker-emulator-1.TOD5mNOt_1q8drI.webp" alt="image" width="1306" height="528" loading="lazy" decoding="async"></p> <h3 id="bar-magnifier" class="md-heading"><a href="#bar-magnifier">Bar magnifier<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>Users with Premium and higher-tier <a href="https://www.tradingview.com/pricing/">plans</a> can override the broker emulator’s default assumptions about intrabar prices by enabling the <a href="https://www.tradingview.com/support/solutions/43000669285">Bar Magnifier</a> backtesting mode. In this mode, the emulator uses data from <em>lower timeframes</em> to obtain more granular information about price action within bars, allowing more precise order fills in the strategy’s simulation.</p> <p>To enable the <a href="https://www.tradingview.com/support/solutions/43000669285">Bar Magnifier</a> mode, include <code dir="auto">use_bar_magnifier = true</code> in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement, or select the “Using bar magnifier” option in the “Fill orders” section of the strategy’s “Settings/Properties” tab.</p> <p>The following example script illustrates how the Bar Magnifier can enhance order-fill behavior. When the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_time">time</a> value crosses the defined <code dir="auto">orderTime</code>, it creates “Buy” and “Exit” <a href="/pine-script-docs/concepts/strategies/#limit-orders">limit orders</a> at the calculated <code dir="auto">entryPrice</code> and <code dir="auto">exitPrice</code>. For visual reference, the script colors the background orange when it places the orders, and it draws two horizontal <a href="/pine-script-docs/concepts/lines-and-boxes/#lines">lines</a> at the order prices:</p> <p><img src="/pine-script-docs/_astro/Strategies-Broker-emulator-Bar-magnifier-1.coZBXeS5_Z73KL6.webp" alt="image" width="1342" height="690" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Bar Magnifier Demo&quot;, overlay = true, use_bar_magnifier = false) //@variable The UNIX timestamp to place the order at. int orderTime = timestamp(&quot;UTC&quot;, 2023, 3, 22, 18) //@variable Is `color.orange` when `time` crosses the `orderTime`, false otherwise. color orderColor = na // Entry and exit prices. float entryPrice = hl2 - (high - low) float exitPrice = entryPrice + (high - low) * 0.25 // Entry and exit lines. var line entryLine = na var line exitLine = na if ta.cross(time, orderTime) // Draw new entry and exit lines. entryLine := line.new(bar_index, entryPrice, bar_index + 1, entryPrice, color = color.green, width = 2) exitLine := line.new(bar_index, exitPrice, bar_index + 1, exitPrice, color = color.red, width = 2) // Update order highlight color. orderColor := color.new(color.orange, 80) // Place limit orders at the `entryPrice` and `exitPrice`. strategy.entry(&quot;Buy&quot;, strategy.long, limit = entryPrice) strategy.exit(&quot;Exit&quot;, &quot;Buy&quot;, limit = exitPrice) // Update lines while the position is open. else if strategy.position_size &gt; 0.0 entryLine.set_x2(bar_index + 1) exitLine.set_x2(bar_index + 1) bgcolor(orderColor)</div> <p>Because the script does not include a <code dir="auto">use_bar_magnifier</code> argument in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> function, the broker emulator uses the default <a href="/pine-script-docs/concepts/strategies/#broker-emulator">assumptions</a> when filling the orders: that the bar’s price moved from open to high, high to low, and then low to close. Therefore, after filling the “Buy” order at the price indicated by the green line, the broker emulator inferred that the market price did not go back up to touch the red line and trigger the “Exit” order. In other words, the strategy <em>could not</em> enter and exit the position on the same bar according to the broker emulator’s assumptions.</p> <p>After we enable the <a href="https://www.tradingview.com/support/solutions/43000669285">Bar Magnifier</a> mode, the broker emulator can access <em>10-minute</em> data on the 60-minute chart instead of relying on its assumptions about hourly bars. On this timeframe, the market price <em>did</em> move back up to the “Exit” order’s price after reaching the “Buy” order’s price in the same hour. Therefore, with the Bar Magnifier enabled in this scenario, both orders execute on the same hourly bar:</p> <p><img src="/pine-script-docs/_astro/Strategies-Broker-emulator-Bar-magnifier-2.BNRDP6RA_1rU9cu.webp" alt="image" width="1342" height="688" loading="lazy" decoding="async"></p> <aside aria-label="Notice!" class="tv-informer not-content" style="--informer-header-color:#FF9800;--informer-back-color-light:#FFF3E0;--informer-back-color-dark:#33261A"><div class="tv-informer-icon"><svg viewBox="0 0 18 18" width="18" height="18"><path fill-rule="evenodd" d="M9 17A8 8 0 1 0 9 1a8 8 0 0 0 0 16ZM9 4c-.79 0-1.38.7-1.25 1.48l.67 4.03a.59.59 0 0 0 1.16 0l.67-4.03A1.27 1.27 0 0 0 9 4Zm0 8a1 1 0 1 0 0 2 1 1 0 0 0 0-2Z" fill="currentColor"></path></svg></div><div class="tv-informer-content"><p><span class="tv-informer-header">Notice!</span>Scripts can request a maximum of 200,000 bars from a lower timeframe. Due to this limitation, some symbols with lengthier history might <em>not</em> have intrabar coverage for their initial chart bars. Enabling the Bar Magnifier mode <strong>does not</strong> affect the trades on chart bars that do not have available intrabar data.</p></div></aside> <h2 id="orders-and-trades" class="md-heading"><a href="#orders-and-trades">Orders and trades<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p>Pine Script™ strategies use orders to make trades and manage positions, similar to real-world trading. In this context, an <em>order</em> is an instruction that a strategy sends to the <a href="/pine-script-docs/concepts/strategies/#broker-emulator">broker emulator</a> to perform a market action, and a <em>trade</em> is the resulting transaction after the emulator fills an order.</p> <p>Let’s take a closer look at how strategy orders work and how they become trades. Every 20 bars, the following script creates a long <a href="/pine-script-docs/concepts/strategies/#market-orders">market order</a> with <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> and draws a <a href="https://www.tradingview.com/pine-script-reference/v6/#type_label">label</a>. It calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close_all">strategy.close_all()</a> on each bar from the global scope to generate a market order to close any open position:</p> <p><img src="/pine-script-docs/_astro/Strategies-Orders-and-entries-1.CX7qCrxg_Z2raUd5.webp" alt="image" width="1342" height="678" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Order execution demo&quot;, &quot;My strategy&quot;, true, margin_long = 100, margin_short = 100) //@function Displays the specified `txt` in a label at the `high` of the current bar. debugLabel(string txt) =&gt; label.new( bar_index, high, text = txt, color=color.lime, style = label.style_label_lower_right, textcolor = color.black, size = size.large ) //@variable Is `true` on every 20th bar, `false` otherwise. bool longCondition = bar_index % 20 == 0 // Draw a label and place a long market order when `longCondition` occurs. if longCondition debugLabel(&quot;Long entry order created&quot;) strategy.entry(&quot;My Long Entry Id&quot;, strategy.long) // Place a closing market order whenever there is an open position. strategy.close_all()</div> <p>Note that:</p> <ul> <li>Although the script calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close_all">strategy.close_all()</a> on every bar, the function only creates a new exit order when the strategy has an <em>open position</em>. If there is no open position, the function call has no effect.</li> </ul> <p>The blue arrows on the above chart show where the strategy entered a long position, and the purple arrows mark the bars where the strategy closed the position. Notice that the <a href="https://www.tradingview.com/pine-script-reference/v6/#type_label">label</a> drawings appear one bar <em>before</em> the entry markers, and the entry markers appear one bar <em>before</em> the closing markers. This sequence illustrates order creation and execution in action.</p> <p>By default, the earliest point the <a href="/pine-script-docs/concepts/strategies/#broker-emulator">broker emulator</a> fills an order is on the next available price tick, because creating and filling an order on the same tick is unrealistic. Since strategies recalculate after each bar closes by default, the next available tick where the emulator fills a generated order is at the <em>open</em> of the <em>following bar</em>. For example, when the <code dir="auto">longCondition</code> occurs on bar 20, the script places an entry order to fill on the next tick, which is at the open of bar 21. When the strategy recalculates its values after bar 21 closes, it places an order to close the current position on the next tick, which is at the open of bar 22.</p> <h2 id="order-types" class="md-heading"><a href="#order-types">Order types<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p>Pine Script™ strategies can simulate different order types to suit specific trading system needs. The main notable order types include <a href="/pine-script-docs/concepts/strategies/#market-orders">market</a>, <a href="/pine-script-docs/concepts/strategies/#limit-orders">limit</a>, <a href="/pine-script-docs/concepts/strategies/#stop-and-stop-limit-orders">stop</a>, and <a href="/pine-script-docs/concepts/strategies/#stop-and-stop-limit-orders">stop-limit</a>.</p> <h3 id="market-orders" class="md-heading"><a href="#market-orders">Market orders<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>A <em>market order</em> is the simplest type of order, which most <a href="/pine-script-docs/concepts/strategies/#order-placement-and-cancellation">order placement commands</a> generate by default. A market order is an instruction to buy or sell a security as soon as possible, irrespective of the price. As such, the <a href="/pine-script-docs/concepts/strategies/#broker-emulator">broker emulator</a> always executes a market order on the next available tick.</p> <p>The example below alternates between placing a long and short market order once every <code dir="auto">lengthInput</code> bars. When the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_bar_index">bar_index</a> is divisible by <code dir="auto">2 * lengthInput</code>, the strategy generates a long market order. Otherwise, it places a short market order when the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_bar_index">bar_index</a> is divisible by the <code dir="auto">lengthInput</code>:</p> <p><img src="/pine-script-docs/_astro/Strategies-Orders-and-entries-Order-types-1.XLQDthDF_Z1YB5yU.webp" alt="image" width="1342" height="680" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Market order demo&quot;, overlay = true, margin_long = 100, margin_short = 100) //@variable Number of bars between long and short entries. int lengthInput = input.int(10, &quot;Cycle length&quot;, 1) //@function Displays the specified `txt` in a label on the current bar. debugLabel(string txt, color lblColor) =&gt; label.new( bar_index, high, text = txt, color = lblColor, textcolor = color.white, style = label.style_label_lower_right, size = size.large ) //@variable Is `true` every `2 * lengthInput` bars, `false` otherwise. longCondition = bar_index % (2 * lengthInput) == 0 //@variable Is `true` every `lengthInput` bars, `false` otherwise. shortCondition = bar_index % lengthInput == 0 // Generate a long market order with a `color.green` label on `longCondition`. if longCondition debugLabel(&quot;Long market order created&quot;, color.green) strategy.entry(&quot;My Long Entry Id&quot;, strategy.long) // Otherwise, generate a short market order with a `color.red` label on `shortCondition`. else if shortCondition debugLabel(&quot;Short market order created&quot;, color.red) strategy.entry(&quot;My Short Entry Id&quot;, strategy.short)</div> <p>Note that:</p> <ul> <li>The <a href="/pine-script-docs/concepts/text-and-shapes/#labels">labels</a> indicate the bars where the script generates the market orders. The broker emulator fills each order at the open of the following bar.</li> <li>The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> command can automatically <em>reverse</em> an open position in the opposite direction. See <a href="/pine-script-docs/concepts/strategies/#reversing-positions">this section</a> below for more information.</li> </ul> <h3 id="limit-orders" class="md-heading"><a href="#limit-orders">Limit orders<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>A <em>limit order</em> is an instruction to buy or sell a security at a specific price or better (lower than specified for long orders, and higher than specified for short orders), irrespective of the time. To simulate a limit order in a strategy script, pass a <em>price</em> value to the <code dir="auto">limit</code> parameter of an applicable <a href="/pine-script-docs/concepts/strategies/#order-placement-and-cancellation">order placement command</a>.</p> <p>When the market price reaches a limit order’s value, or crosses it in the favorable direction, the <a href="/pine-script-docs/concepts/strategies/#broker-emulator">broker emulator</a> fills the order at that value or a better price. When a strategy generates a limit order at a <em>worse</em> value than the current market price (higher for long orders and lower for short orders), the emulator fills the order without waiting for the market price to reach that value.</p> <p>For example, the following script generates a long limit order 800 ticks below the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_close">close</a> of the bar 100 bars before the last chart bar using the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> command. It draws a <a href="https://www.tradingview.com/pine-script-reference/v6/#type_label">label</a> to signify the bar where the strategy created the order and a <a href="https://www.tradingview.com/pine-script-reference/v6/#type_line">line</a> to visualize the order’s price:</p> <p><img src="/pine-script-docs/_astro/Strategies-Orders-and-entries-Order-types-2.Ma_eheTS_1mD31p.webp" alt="image" width="1342" height="680" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Limit order demo&quot;, overlay = true, margin_long = 100, margin_short = 100) //@function Displays text passed to `txt` and a horizontal line at `price` when called. debugLabel(float price, string txt) =&gt; label.new( bar_index, price, text = txt, color = color.teal, textcolor = color.white, style = label.style_label_lower_right, size = size.large ) line.new( bar_index, price, bar_index + 1, price, color = color.teal, extend = extend.right, style = line.style_dashed ) // Generate a long limit order with a label and line 100 bars before the `last_bar_index`. if last_bar_index - bar_index == 100 limitPrice = close - syminfo.mintick * 800 debugLabel(limitPrice, &quot;Long Limit order created&quot;) strategy.entry(&quot;Long&quot;, strategy.long, limit = limitPrice)</div> <p>Notice that in the chart above, the <a href="https://www.tradingview.com/pine-script-reference/v6/#type_label">label</a> and the start of the <a href="https://www.tradingview.com/pine-script-reference/v6/#type_line">line</a> occurred several bars before the “Long” entry marker. The <a href="/pine-script-docs/concepts/strategies/#broker-emulator">broker emulator</a> could not fill the order while the market price remained <em>above</em> the <code dir="auto">limitPrice</code> because such a price is a <em>worse</em> value for the long trade. After the price fell and reached the <code dir="auto">limitPrice</code>, the emulator filled the order mid-bar at that value.</p> <p>If we set the <code dir="auto">limitPrice</code> to a value <em>above</em> the bar’s <a href="https://www.tradingview.com/pine-script-reference/v6/#var_close">close</a> rather than <em>below</em>, the broker emulator fills the order at the open of the following bar because the closing price is already a more <em>favorable</em> value for the long trade. Here, we set the <code dir="auto">limitPrice</code> in the script to 800 ticks above the bar’s <a href="https://www.tradingview.com/pine-script-reference/v6/#var_close">close</a> to demonstrate this effect:</p> <p><img src="/pine-script-docs/_astro/Strategies-Orders-and-entries-Order-types-3.D5qNWPW8_Ad7IE.webp" alt="image" width="1342" height="680" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Limit order demo&quot;, overlay = true, margin_long = 100, margin_short = 100) //@function Displays text passed to `txt` and a horizontal line at `price` when called. debugLabel(float price, string txt) =&gt; label.new( bar_index, price, text = txt, color = color.teal, textcolor = color.white, style = label.style_label_lower_right, size = size.large ) line.new( bar_index, price, bar_index + 1, price, color = color.teal, extend = extend.right, style = line.style_dashed ) // Generate a long limit order with a label and line 100 bars before the `last_bar_index`. if last_bar_index - bar_index == 100 limitPrice = close + syminfo.mintick * 800 debugLabel(limitPrice, &quot;Long Limit order created&quot;) strategy.entry(&quot;Long&quot;, strategy.long, limit = limitPrice)</div> <h3 id="stop-and-stop-limit-orders" class="md-heading"><a href="#stop-and-stop-limit-orders">Stop and stop-limit orders<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>A <em>stop order</em> is an instruction to activate a new <a href="/pine-script-docs/concepts/strategies/#market-orders">market</a> or <a href="/pine-script-docs/concepts/strategies/#limit-orders">limit</a> order when the market price reaches a specific price or a worse value (higher than specified for long orders and lower than specified for short orders). To simulate a stop order, pass a price value to the <code dir="auto">stop</code> parameter of an applicable <a href="/pine-script-docs/concepts/strategies/#order-placement-and-cancellation">order placement command</a>.</p> <p>When a strategy generates a stop order at a <em>better</em> value than the current market price, it activates the subsequent order without waiting for the market price to reach that value.</p> <p>The following example calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> to place a stop order 800 ticks above the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_close">close</a> 100 bars before the last historical chart bar. It also draws a <a href="https://www.tradingview.com/pine-script-reference/v6/#type_label">label</a> on the bar where it created the order and a <a href="https://www.tradingview.com/pine-script-reference/v6/#type_line">line</a> to display the stop price. As we see in the chart below, the strategy entered a long position immediately after the price crossed the stop level:</p> <p><img src="/pine-script-docs/_astro/Strategies-Orders-and-entries-Order-types-4.BpjXSFRL_ZCMq1X.webp" alt="image" width="1342" height="680" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Stop order demo&quot;, overlay = true, margin_long = 100, margin_short = 100) //@function Displays text passed to `txt` when called and shows the `price` level on the chart. debugLabel(price, txt) =&gt; label.new( bar_index, high, text = txt, color = color.teal, textcolor = color.white, style = label.style_label_lower_right, size = size.large ) line.new(bar_index, high, bar_index, price, style = line.style_dotted, color = color.teal) line.new( bar_index, price, bar_index + 1, price, color = color.teal, extend = extend.right, style = line.style_dashed ) // Generate a long stop order with a label and lines 100 bars before the last bar. if last_bar_index - bar_index == 100 stopPrice = close + syminfo.mintick * 800 debugLabel(stopPrice, &quot;Long Stop order created&quot;) strategy.entry(&quot;Long&quot;, strategy.long, stop = stopPrice)</div> <p>Note that:</p> <ul> <li>A basic stop order is essentially the opposite of a <a href="/pine-script-docs/concepts/strategies/#limit-orders">limit order</a> in terms of its execution based on the market price. If we use a limit order instead of a stop order in this scenario, the order executes immediately on the next bar. See the <a href="/pine-script-docs/concepts/strategies/#limit-orders">previous section</a> for an example.</li> </ul> <p>When a <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> or <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> call includes a <code dir="auto">stop</code> <em>and</em> <code dir="auto">limit</code> argument, it creates a <em>stop-limit order</em>. Unlike a basic stop order, which triggers a <a href="/pine-script-docs/concepts/strategies/#market-orders">market order</a> when the current price is at the <code dir="auto">stop</code> level or a worse value, a stop-limit order creates a subsequent <a href="/pine-script-docs/concepts/strategies/#limit-orders">limit order</a> to fill at the specified <code dir="auto">limit</code> price.</p> <p>Below, we modified the previous script to simulate and visualize a stop-limit order. This script version includes the bar’s <a href="https://www.tradingview.com/pine-script-reference/v6/#var_low">low</a> as the <code dir="auto">limit</code> price in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> command. It also includes additional drawings to show where the strategy activated the subsequent limit order and to visualize the limit price.</p> <p>In this example chart, notice how the market price reached the limit level on the next bar after the stop-limit order was created, but the strategy did not enter a position because the limit order was not yet active. After price later reached the stop level, the strategy placed the limit order, and then the <a href="/pine-script-docs/concepts/strategies/#broker-emulator">broker emulator</a> filled it after the market price dropped back down to the limit level:</p> <p><img src="/pine-script-docs/_astro/Strategies-Orders-and-entries-Order-types-5.CduO1Nxw_2mnPeh.webp" alt="image" width="1342" height="680" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Stop-Limit order demo&quot;, overlay = true, margin_long = 100, margin_short = 100) //@function Displays text passed to `txt` when called and shows the `price` level on the chart. debugLabel(price, txt, lblColor, lineWidth = 1) =&gt; label.new( bar_index, high, text = txt, color = lblColor, textcolor = color.white, style = label.style_label_lower_right, size = size.large ) line.new(bar_index, close, bar_index, price, style = line.style_dotted, color = lblColor, width = lineWidth) line.new( bar_index, price, bar_index + 1, price, color = lblColor, extend = extend.right, style = line.style_dashed, width = lineWidth ) var float stopPrice = na var float limitPrice = na // Generate a long stop-limit order with a label and lines 100 bars before the last bar. if last_bar_index - bar_index == 100 stopPrice := close + syminfo.mintick * 800 limitPrice := low debugLabel(limitPrice, &quot;&quot;, color.gray) debugLabel(stopPrice, &quot;Long Stop-Limit order created&quot;, color.teal) strategy.entry(&quot;Long&quot;, strategy.long, stop = stopPrice, limit = limitPrice) // Draw a line and label when the strategy activates the limit order. if high &gt;= stopPrice debugLabel(limitPrice, &quot;Limit order activated&quot;, color.green, 2) stopPrice := na</div> <h2 id="order-placement-and-cancellation" class="md-heading"><a href="#order-placement-and-cancellation">Order placement and cancellation<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p>The <code dir="auto">strategy.*</code> namespace features the following five functions that simulate the placement of orders, known as <em>order placement commands</em>: <a href="/pine-script-docs/concepts/strategies/#strategyentry">strategy.entry()</a>, <a href="/pine-script-docs/concepts/strategies/#strategyorder">strategy.order()</a>, <a href="/pine-script-docs/concepts/strategies/#strategyexit">strategy.exit()</a>, <a href="/pine-script-docs/concepts/strategies/#strategyclose-and-strategyclose_all">strategy.close()</a>, and <a href="/pine-script-docs/concepts/strategies/#strategyclose-and-strategyclose_all">strategy.close_all()</a>.</p> <p>Additionally, the namespace includes the following two functions that cancel pending orders, known as <em>order cancellation commands</em>: <a href="/pine-script-docs/concepts/strategies/#strategycancel-and-strategycancel_all">strategy.cancel()</a> and <a href="/pine-script-docs/concepts/strategies/#strategycancel-and-strategycancel_all">strategy.cancel_all()</a>.</p> <p>The segments below explain these commands, their unique characteristics, and how to use them.</p> <h3 id="strategyentry" class="md-heading"><a href="#strategyentry">`strategy.entry()`<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> command generates <em>entry orders</em>. Its unique features help simplify opening and managing positions. This order placement command generates <a href="/pine-script-docs/concepts/strategies/#market-orders">market orders</a> by default. It can also create <a href="/pine-script-docs/concepts/strategies/#limit-orders">limit</a>, <a href="/pine-script-docs/concepts/strategies/#stop-and-stop-limit-orders">stop</a>, and <a href="/pine-script-docs/concepts/strategies/#stop-and-stop-limit-orders">stop-limit</a> orders with the <code dir="auto">limit</code> and <code dir="auto">stop</code> parameters, as explained in the <a href="/pine-script-docs/concepts/strategies/#order-types">Order types</a> section above.</p> <h4 id="reversing-positions" class="md-heading"><a href="#reversing-positions">Reversing positions<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h4> <p>One of the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> command’s unique features is its ability to <em>reverse</em> an open position automatically. By default, when an order from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> executes while there is an open position in the opposite direction, the command automatically <em>adds</em> the position’s size to the new order’s size. The added quantity allows the order to close the current position and open a new position for the specified number of contracts/lots/shares/units in the new direction.</p> <p>For instance, if a strategy has an open position of 15 shares in the <a href="https://www.tradingview.com/pine-script-reference/v6/#const_strategy.long">strategy.long</a> direction and calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> to place a new <a href="/pine-script-docs/concepts/strategies/#market-orders">market order</a> in the <a href="https://www.tradingview.com/pine-script-reference/v6/#const_strategy.short">strategy.short</a> direction, the size of the resulting transaction is the specified entry size <strong>plus</strong> 15 shares.</p> <p>The example below demonstrates this behavior in action. When the <code dir="auto">buyCondition</code> occurs once every 100 bars, the script calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> with <code dir="auto">qty = 15</code> to open a long position of 15 shares. Otherwise, when the <code dir="auto">sellCondition</code> occurs on every 50th bar, the script calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> with <code dir="auto">qty = 5</code> to enter a new short position of five shares. The script also highlights the chart’s background on the bars where the <code dir="auto">buyCondition</code> and <code dir="auto">sellCondition</code> occurs:</p> <p><img src="/pine-script-docs/_astro/Strategies-Order-placement-and-cancellation-Strategy-entry-Reversing-positions-1.Cs1E9UJf_Z2uYkzU.webp" alt="image" width="1336" height="548" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Reversing positions demo&quot;, overlay = true) //@variable Is `true` on every 100th bar, `false` otherwise. bool buyCondition = bar_index % 100 == 0 //@variable Is `true` on every 50th bar, `false` otherwise. bool sellCondition = bar_index % 50 == 0 if buyCondition // Place a &quot;buy&quot; market order to close the short position and enter a long position of 15 shares. strategy.entry(&quot;buy&quot;, strategy.long, qty = 15) else if sellCondition // Place a &quot;sell&quot; market order to close the long position and enter a short position of 5 shares. strategy.entry(&quot;sell&quot;, strategy.short, qty = 5) // Highlight the background when the `buyCondition` or `sellCondition` occurs. bgcolor(buyCondition ? color.new(color.blue, 90) : sellCondition ? color.new(color.red, 90) : na)</div> <p>The trade markers on the chart show the <em>transaction size</em>, not the size of the resulting position. The markers above show that the transaction size was <em>20 shares</em> on each order fill rather than 15 for long orders and five for short orders. Since <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> reverses a position in the opposite direction by default, each call <em>adds</em> the open position’s size (e.g., 15 for long entries) to the new order’s size (e.g., 5 for short entries), resulting in a quantity of 20 shares on each entry after the first. Although each of these <em>transactions</em> is 20 shares in size, the resulting positions are 5 shares for each short entry and 15 for each long entry.</p> <p>Note that:</p> <ul> <li>The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.risk.allow_entry_in">strategy.risk.allow_entry_in()</a> function <em>overrides</em> the allowed direction for the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> command. When a script specifies a trade direction with this <a href="/pine-script-docs/concepts/strategies/#risk-management">risk management</a> command, orders from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> in the opposite direction <em>close</em> the open position without allowing a reversal.</li> </ul> <h4 id="pyramiding" class="md-heading"><a href="#pyramiding">Pyramiding<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h4> <p>Another unique characteristic of the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> command is its connection to a strategy’s <em>pyramiding</em> property. Pyramiding specifies the maximum number of <em>successive entries</em> a strategy allows in the same direction. Users can set this property by including a <code dir="auto">pyramiding</code> argument in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement or by adjusting the “Pyramiding” input in the script’s “Settings/Properties” tab. The default value is 1, meaning the strategy can open new positions but cannot add to them using orders from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> calls.</p> <p>The following example uses <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> to place a <a href="/pine-script-docs/concepts/strategies/#market-orders">market order</a> when the <code dir="auto">entryCondition</code> occurs on every 25th bar. The direction of the orders changes once every 100 bars, meaning every 100-bar cycle includes <em>four</em> <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> calls with the same direction. For visual reference of the conditions, the script highlights the chart’s background based on the current direction each time the <code dir="auto">entryCondition</code> occurs:</p> <p><img src="/pine-script-docs/_astro/Strategies-Order-placement-and-cancellation-Strategy-entry-Pyramiding-1.C1FbnbUX_ZfqMKR.webp" alt="image" width="1336" height="546" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Pyramiding demo&quot;, overlay = true) //@variable Represents the direction of the entry orders. A value of 1 means long, and -1 means short. var int direction = 1 //@variable Is `true` once every 25 bars, `false` otherwise. bool entryCondition = bar_index % 25 == 0 // Change the `direction` on every 100th bar. if bar_index % 100 == 0 direction *= -1 // Place a market order based on the current `direction` when the `entryCondition` occurs. if entryCondition strategy.entry(&quot;Entry&quot;, direction == 1 ? strategy.long : strategy.short) //@variable When the `entryCondition` occurs, is a blue color if the `direction` is 1 and a red color otherwise. color bgColor = entryCondition ? (direction == 1 ? color.new(color.blue, 80) : color.new(color.red, 80)) : na // Highlight the chart&#39;s background using the `bgColor`. bgcolor(bgColor, title = &quot;Background highlight&quot;)</div> <p>Notice that although the script calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> with the same direction four times within each 100-bar cycle, the strategy <em>does not</em> execute an order after every call. It cannot open more than one trade per position with <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> because it uses the default pyramiding value of 1.</p> <p>Below, we modified the script by including <code dir="auto">pyramiding = 4</code> in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement to allow up to four successive trades in the same direction. Now, an order fill occurs after every <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> call:</p> <p><img src="/pine-script-docs/_astro/Strategies-Order-placement-and-cancellation-Strategy-entry-Pyramiding-2.CgMebGaG_1nl0aE.webp" alt="image" width="1336" height="548" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Pyramiding demo&quot;, overlay = true, pyramiding = 4) //@variable Represents the direction of the entry orders. A value of 1 means long, and -1 means short. var int direction = 1 //@variable Is `true` once every 25 bars, `false` otherwise. bool entryCondition = bar_index % 25 == 0 // Change the `direction` on every 100th bar. if bar_index % 100 == 0 direction *= -1 // Place a market order based on the current `direction` when the `entryCondition` occurs. if entryCondition strategy.entry(&quot;Entry&quot;, direction == 1 ? strategy.long : strategy.short) //@variable When the `entryCondition` occurs, is a blue color if the `direction` is 1 and a red color otherwise. color bgColor = entryCondition ? (direction == 1 ? color.new(color.blue, 80) : color.new(color.red, 80)) : na // Highlight the chart&#39;s background using the `bgColor`. bgcolor(bgColor, title = &quot;Background highlight&quot;)</div> <h3 id="strategyorder" class="md-heading"><a href="#strategyorder">`strategy.order()`<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> command generates a <em>basic order</em>. Unlike other order placement commands, which can behave differently based on a strategy’s properties and open trades, this command <em>ignores</em> most properties, such as <a href="/pine-script-docs/concepts/strategies/#pyramiding">pyramiding</a>, and simply creates orders with the specified parameters. This command generates <a href="/pine-script-docs/concepts/strategies/#market-orders">market orders</a> by default. It can also create <a href="/pine-script-docs/concepts/strategies/#limit-orders">limit</a>, <a href="/pine-script-docs/concepts/strategies/#stop-and-stop-limit-orders">stop</a>, and <a href="/pine-script-docs/concepts/strategies/#stop-and-stop-limit-orders">stop-limit</a> orders with the <code dir="auto">limit</code> and <code dir="auto">stop</code> parameters. Orders from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> can open new positions and modify or close existing ones. When a strategy executes an order from this command, the resulting market position is the <em>net sum</em> of the open position and the filled order quantity.</p> <p>The following script uses <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> calls to enter and exit positions. The strategy places a long <a href="/pine-script-docs/concepts/strategies/#market-orders">market order</a> for 15 units once every 100 bars. On every 25th bar that is not a multiple of 100, it places a short market order for five units. The script highlights the background to signify where the strategy places a “buy” or “sell” order:</p> <p><img src="/pine-script-docs/_astro/Strategies-Orders-and-entries-Order-placement-commands-3.DSecmQ5U_Zz9mM4.webp" alt="image" width="1342" height="680" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;`strategy.order()` demo&quot;, overlay = true) //@variable Is `true` on every 100th bar, `false` otherwise. bool buyCondition = bar_index % 100 == 0 //@variable Is `true` on every 25th bar, `false` otherwise. bool sellCondition = bar_index % 25 == 0 if buyCondition // Place a &quot;buy&quot; market order to trade 15 units in the long direction. strategy.order(&quot;buy&quot;, strategy.long, qty = 15) else if sellCondition // Place a &quot;sell&quot; market order to trade 5 units in the short direction. strategy.order(&quot;sell&quot;, strategy.short, qty = 5) // Highlight the background when the `buyCondition` or `sellCondition` occurs. bgcolor(buyCondition ? color.new(color.blue, 90) : sellCondition ? color.new(color.red, 90) : na)</div> <p>This particular strategy never simulates a <em>short position</em>. Unlike the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> command, <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> <em>does not</em> automatically <a href="/pine-script-docs/concepts/strategies/#reversing-positions">reverse</a> open positions. After filling a “buy” order, the strategy has an open long position of 15 units. The three subsequent “sell” orders <em>reduce</em> the position by five units each, and 15 - 5 * 3 = 0. In other words, the strategy opens a long position on every 100th bar and gradually reduces the size to 0 using three successive short orders. If we used <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> instead of the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> command in this example, the strategy would alternate between entering long and short positions of 15 and five units, respectively.</p> <h3 id="strategyexit" class="md-heading"><a href="#strategyexit">`strategy.exit()`<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> command generates <em>exit orders</em>. It features several unique behaviors that link to open trades, helping to simplify closing market positions and creating multi-level exits with <em>take-profit</em>, <em>stop-loss</em>, and <em>trailing stop</em> orders.</p> <p>Unlike other order placement commands, which can generate a <em>single order</em> per call, each call to <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> can produce <em>more than one</em> type of exit order, depending on its arguments. Additionally, a single call to this command can generate exit orders for <em>multiple entries</em>, depending on the specified <code dir="auto">from_entry</code> value and the strategy’s open trades.</p> <h4 id="take-profit-and-stop-loss" class="md-heading"><a href="#take-profit-and-stop-loss">Take-profit and stop-loss<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h4> <p>The most basic use of the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> command is the placement of <a href="/pine-script-docs/concepts/strategies/#limit-orders">limit orders</a> to trigger exits after earning enough money (take-profit), <a href="/pine-script-docs/concepts/strategies/#stop-and-stop-limit-orders">stop orders</a> to trigger exits after losing too much money (stop-loss), or both (bracket).</p> <p>Four parameters determine the prices of the command’s take-profit and stop-loss orders:</p> <ul> <li>The <code dir="auto">profit</code> and <code dir="auto">loss</code> parameters accept <em>relative</em> values representing the number of <em>ticks</em> the market price must move away from the entry price to trigger an exit.</li> <li>The <code dir="auto">limit</code> and <code dir="auto">stop</code> parameters accept <em>absolute</em> values representing the specific <em>prices</em> that trigger an exit when the market price reaches them.</li> </ul> <p>The absolute parameters of the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> command <em>supersede</em> the relative ones. If a <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call contains <code dir="auto">profit</code> and <code dir="auto">limit</code> arguments, it creates a take-profit order at the <code dir="auto">limit</code> price and ignores the <code dir="auto">profit</code> value. Likewise, if the call includes <code dir="auto">loss</code> and <code dir="auto">stop</code> arguments, the command ignores the <code dir="auto">loss</code> value and places a stop-loss order at the <code dir="auto">stop</code> price.</p> <aside aria-label="Notice!" class="tv-informer not-content" style="--informer-header-color:#FF9800;--informer-back-color-light:#FFF3E0;--informer-back-color-dark:#33261A"><div class="tv-informer-icon"><svg viewBox="0 0 18 18" width="18" height="18"><path fill-rule="evenodd" d="M9 17A8 8 0 1 0 9 1a8 8 0 0 0 0 16ZM9 4c-.79 0-1.38.7-1.25 1.48l.67 4.03a.59.59 0 0 0 1.16 0l.67-4.03A1.27 1.27 0 0 0 9 4Zm0 8a1 1 0 1 0 0 2 1 1 0 0 0 0-2Z" fill="currentColor"></path></svg></div><div class="tv-informer-content"><p><span class="tv-informer-header">Notice!</span>The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> command’s <code dir="auto">limit</code> and <code dir="auto">stop</code> parameters <strong>do not</strong> behave the same as the <code dir="auto">limit</code> and <code dir="auto">stop</code> parameters of the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> commands. Calling <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> or <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> with <code dir="auto">limit</code> and <code dir="auto">stop</code> arguments creates a single <a href="/pine-script-docs/concepts/strategies/#stop-and-stop-limit-orders">stop-limit order</a>. In contrast, calling <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> with both arguments creates <strong>two exit orders</strong>: a take-profit order at the <code dir="auto">limit</code> price and a stop-loss order at the <code dir="auto">stop</code> price.</p></div></aside> <p>The following example creates exit bracket (take-profit and stop-loss) orders with the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> command. When the <code dir="auto">buyCondition</code> occurs, the script calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> to place a “buy” <a href="/pine-script-docs/concepts/strategies/#market-orders">market order</a>. It also calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> with <code dir="auto">limit</code> and <code dir="auto">stop</code> arguments to create a take-profit order at the <code dir="auto">limitPrice</code> and a stop-loss order at the <code dir="auto">stopPrice</code>. The script plots the <code dir="auto">limitPrice</code> and <code dir="auto">stopPrice</code> values on the chart to visualize the exit order prices:</p> <p><img src="/pine-script-docs/_astro/Strategies-Order-placement-and-cancellation-Strategy-exit-Take-profit-and-stop-loss-1.B0PJXuvg_17dSOG.webp" alt="image" width="1336" height="514" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Take-profit and stop-loss demo&quot;, overlay = true) //@variable Is `true` on every 100th bar. bool buyCondition = bar_index % 100 == 0 //@variable The current take-profit order price. var float takeProfit = na //@variable The current stop-loss order price. var float stopLoss = na if buyCondition // Update the `takeProfit` and `stopLoss` values. if strategy.opentrades == 0 takeProfit := close * 1.01 stopLoss := close * 0.99 // Place a long market order. strategy.entry(&quot;buy&quot;, strategy.long) // Place a take-profit order at the `takeProfit` price and a stop-loss order at the `stopLoss` price. strategy.exit(&quot;exit&quot;, &quot;buy&quot;, limit = takeProfit, stop = stopLoss) // Set `takeProfit` and `stopLoss` to `na` when the position closes. if ta.change(strategy.closedtrades) &gt; 0 takeProfit := na stopLoss := na // Plot the `takeProfit` and `stopLoss` values. plot(takeProfit, &quot;TP&quot;, color.green, style = plot.style_circles) plot(stopLoss, &quot;SL&quot;, color.red, style = plot.style_circles)</div> <p>Note that:</p> <ul> <li>We did not specify a <code dir="auto">qty</code> or <code dir="auto">qty_percent</code> argument in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call, meaning it creates orders to exit 100% of the “buy” order’s size.</li> <li>The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> command’s exit orders <em>do not</em> necessarily execute at the specified prices. Strategies can fill <a href="/pine-script-docs/concepts/strategies/#limit-orders">limit orders</a> at <em>better</em> prices and <a href="/pine-script-docs/concepts/strategies/#stop-and-stop-limit-orders">stop orders</a> at <em>worse</em> prices, depending on the range of values available to the <a href="/pine-script-docs/concepts/strategies/#broker-emulator">broker emulator</a>.</li> </ul> <p>When a <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call includes a <code dir="auto">from_entry</code> argument, the resulting exit orders only apply to existing entry orders that have a matching ID. If the specified <code dir="auto">from_entry</code> value does not match the ID of any entry in the current position, the command <em>does not</em> create any exit orders.</p> <p>Below, we changed the <code dir="auto">from_entry</code> argument of the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call in our previous script to “buy2”, which means it creates exit orders only for open trades with the “buy2” entry ID. This version does not place <em>any</em> exit orders because it does not create any entry orders with the “buy2” ID:</p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Invalid `from_entry` ID demo&quot;, overlay = true) //@variable Is `true` on every 100th bar. bool buyCondition = bar_index % 100 == 0 //@variable The current take-profit order price. var float takeProfit = na //@variable The current stop-loss order price. var float stopLoss = na if buyCondition // Update the `takeProfit` and `stopLoss` values before entering the trade. if strategy.opentrades == 0 takeProfit := close * 1.01 stopLoss := close * 0.99 // Place a long market order. strategy.entry(&quot;buy&quot;, strategy.long) // Attempt to place an exit bracket for &quot;buy2&quot; entries. // This call has no effect because the strategy does not create entry orders with the &quot;buy2&quot; ID. strategy.exit(&quot;exit&quot;, &quot;buy2&quot;, limit = takeProfit, stop = stopLoss) // Set `takeProfit` and `stopLoss` to `na` when the position closes. if ta.change(strategy.closedtrades) &gt; 0 takeProfit := na stopLoss := na // Plot the `takeProfit` and `stopLoss` values. plot(takeProfit, &quot;TP&quot;, color.green, style = plot.style_circles) plot(stopLoss, &quot;SL&quot;, color.red, style = plot.style_circles)</div> <p>Note that:</p> <ul> <li>When a <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call <em>does not</em> include a <code dir="auto">from_entry</code> argument, it creates exit orders for <em>all</em> the position’s open trades, regardless of their entry IDs. See the <a href="/pine-script-docs/concepts/strategies/#exits-for-multiple-entries">Exits for multiple entries</a> section below to learn more.</li> </ul> <h4 id="partial-and-multi-level-exits" class="md-heading"><a href="#partial-and-multi-level-exits">Partial and multi-level exits<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h4> <p>Strategies can use more than one call to <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> to create successive <em>partial</em> exit orders for the same entry ID, helping to simplify the formation of multi-level exit strategies. To use multiple <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> calls to exit from an open trade, include a <code dir="auto">qty</code> or <code dir="auto">qty_percent</code> argument in each call to specify how much of the traded quantity to close. If the sum of the exit order sizes exceeds the open position, the strategy automatically <em>reduces</em> their sizes to match the position.</p> <p>Note that:</p> <ul> <li>When a <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call includes <em>both</em> <code dir="auto">qty</code> and <code dir="auto">qty_percent</code> arguments, the command uses the <code dir="auto">qty</code> value to size the order and ignores the <code dir="auto">qty_percent</code> value.</li> </ul> <p>This example demonstrates a simple strategy that creates two partial exit order brackets for an entry ID. When the <code dir="auto">buyCondition</code> occurs, the script places a “buy” <a href="/pine-script-docs/concepts/strategies/#market-orders">market order</a> for two shares with <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a>, and it creates “exit1” and “exit2” brackets using two calls to <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a>. The first call uses a <code dir="auto">qty</code> of 1, and the second uses a <code dir="auto">qty</code> of 3:</p> <p><img src="/pine-script-docs/_astro/Strategies-Orders-and-entries-Order-placement-commands-5.WJU0XPdU_11c8yK.webp" alt="image" width="1342" height="680" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Multi-level exit demo&quot;, &quot;test&quot;, overlay = true) //@variable Is `true` on every 100th bar. bool buyCondition = bar_index % 100 == 0 //@variable The take-profit price for &quot;exit1&quot; orders. var float takeProfit1 = na //@variable The take-profit price for &quot;exit2&quot; orders. var float takeProfit2 = na //@variable The stop-loss price for &quot;exit1&quot; orders. var float stopLoss1 = na //@variable The stop-loss price for &quot;exit2&quot; orders. var float stopLoss2 = na if buyCondition // Update the `takeProfit*` and `stopLoss*` values before entering the trade. if strategy.opentrades == 0 takeProfit1 := close * 1.01 takeProfit2 := close * 1.02 stopLoss1 := close * 0.99 stopLoss2 := close * 0.98 // Place a long market order with a `qty` of 2. strategy.entry(&quot;buy&quot;, strategy.long, qty = 2) // Place an &quot;exit1&quot; bracket with a `qty` of 1 at the `takeProfit1` and `stopLoss1` prices. strategy.exit(&quot;exit1&quot;, &quot;buy&quot;, limit = takeProfit1, stop = stopLoss1, qty = 1) // Place an &quot;exit2&quot; bracket with a `qty` of 3 at the `takeProfit1` and `stopLoss1` prices. // The size of the resulting orders decreases to match the open position. strategy.exit(&quot;exit2&quot;, &quot;buy&quot;, limit = takeProfit2, stop = stopLoss2, qty = 3) // Set `takeProfit1` and `stopLoss1` to `na` when the price touches either value. if high &gt;= takeProfit1 or low &lt;= stopLoss1 takeProfit1 := na stopLoss1 := na // Set `takeProfit2` and `stopLoss2` to `na` when the price touches either value. if high &gt;= takeProfit2 or low &lt;= stopLoss2 takeProfit2 := na stopLoss2 := na // Plot the `takeProfit*` and `stopLoss*` values. plot(takeProfit1, &quot;TP1&quot;, color.green, style = plot.style_circles) plot(takeProfit2, &quot;TP2&quot;, color.green, style = plot.style_circles) plot(stopLoss1, &quot;SL1&quot;, color.red, style = plot.style_circles) plot(stopLoss2, &quot;SL2&quot;, color.red, style = plot.style_circles)</div> <p>As we can see from the trade markers on the chart above, the strategy first executes the “exit1” take-profit or stop-loss order to reduce the open position by one share, leaving one remaining share in the position. However, we specified a size of <em>three shares</em> for the “exit2” order bracket, which exceeds the remaining position. Rather than using this specified quantity, the strategy automatically <em>reduces</em> the “exit2” orders to one share, allowing it to close the position successfully.</p> <p>Note that:</p> <ul> <li>This strategy only fills <strong>one</strong> exit order from the “exit1” bracket, <strong>not both</strong>. When a <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call generates more than one exit order type for an entry ID, the strategy fills the only the <em>first</em> triggered one and automatically cancels the others.</li> <li>The strategy reduced the “exit2” orders because all orders from the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> calls automatically belong to the same <a href="https://www.tradingview.com/pine-script-reference/v6/#const_strategy.oca.reduce">strategy.oca.reduce</a> group by default. Learn more about <a href="/pine-script-docs/concepts/strategies/#oca-groups">OCA groups</a> below.</li> </ul> <p>When creating multiple exit orders with <em>different</em> <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> calls, it’s crucial to note that the orders from each call <em>reserve</em> a portion of the open position. The orders from one <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call <em>cannot</em> exit the portion of a position that a previous call already reserved.</p> <p>For example, this script generates a “buy” entry order for 20 shares with a <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> call and “limit” and “stop” exit orders with two separate calls to <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> 100 bars before the last chart bar. We specified a quantity of 19 shares for the “limit” order and 20 for the “stop” order:</p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Reserved exit demo&quot;, &quot;test&quot;, overlay = true) //@variable The price of the &quot;limit&quot; exit order. var float limitPrice = na //@variable The price of the &quot;stop&quot; exit order. var float stopPrice = na //@variable Is `true` 100 bars before the last chart bar. bool longCondition = last_bar_index - bar_index == 100 if longCondition // Update the `limitPrice` and `stopPrice`. limitPrice := close * 1.01 stopPrice := close * 0.99 // Place a long market order for 20 shares. strategy.entry(&quot;buy&quot;, strategy.long, 20) // Create a take-profit order for 19 shares at the `limitPrice`. strategy.exit(&quot;limit&quot;, limit = limitPrice, qty = 19) // Create a stop-loss order at the `stopPrice`. Although this call specifies a `qty` of 20, the previous // `strategy.exit()` call reserved 19, meaning this call creates an exit order for only 1 share. strategy.exit(&quot;stop&quot;, stop = stopPrice, qty = 20) //@variable Is `true` when the strategy has an open position, `false` otherwise. bool showPlot = strategy.opentrades == 1 // Plot the `limitPrice` and `stopPrice` when `showPlot` is `true`. plot(showPlot ? limitPrice : na, &quot;Limit (take-profit) price&quot;, color.green, 2, plot.style_linebr) plot(showPlot ? stopPrice : na, &quot;Stop (stop-loss) price&quot;, color.red, 2, plot.style_linebr)</div> <p>Users unfamiliar with the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> command’s unique behaviors might expect this strategy to close the entire market position if it fills the “stop” order before the “limit” order. However, the trade markers in the chart below show that the “stop” order only reduces the position by <strong>one share</strong>. The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call for the “limit” order executes first in the code, reserving 19 shares of the open position for closure with that order. This reservation leaves only one share available for the “stop” order to close, regardless of when the strategy fills it:</p> <p><img src="/pine-script-docs/_astro/Strategies-Orders-and-entries-Order-placement-commands-5a.CVJyBloz_1r0nNp.webp" alt="image" width="1342" height="680" loading="lazy" decoding="async"></p> <h4 id="trailing-stops" class="md-heading"><a href="#trailing-stops">Trailing stops<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h4> <p>One of the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> command’s key features is its ability to create <em>trailing stops</em>, i.e., stop-loss orders that trail behind the market price by a specified amount whenever it moves to a better value in the favorable direction (upward for long positions and downward for short positions).</p> <p>This type of exit order has two components: an <em>activation level</em> and a <em>trail offset</em>. The activation level is the value the market price must cross to activate the trailing stop calculation, and the trail offset is the distance the activated stop follows behind the price as it reaches successively better values.</p> <p>Three <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> parameters determine the activation level and trail offset of a trailing stop order:</p> <ul> <li>The <code dir="auto">trail_price</code> parameter accepts an <em>absolute price value</em> for the trailing stop’s activation level.</li> <li>The <code dir="auto">trail_points</code> parameter is an alternative way to specify the activation level. Its value represents the <em>tick distance</em> from the entry price required to activate the trailing stop.</li> <li>The <code dir="auto">trail_offset</code> parameter accepts a value representing the order’s trail offset as a specified number of ticks.</li> </ul> <p>To create and activate a trailing stop order, a <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call must include a <code dir="auto">trail_offset</code> argument and either a <code dir="auto">trail_price</code> or <code dir="auto">trail_points</code> argument. If the call contains both <code dir="auto">trail_price</code> and <code dir="auto">trail_points</code> arguments, the command uses the <code dir="auto">trail_price</code> for the activation level and ignores the <code dir="auto">trail_points</code> value.</p> <p>The example below demonstrates how a trailing stop order works. The strategy places a “Long” <a href="/pine-script-docs/concepts/strategies/#market-orders">market order</a> with the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> command 100 bars before the last chart bar, and it calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> with <code dir="auto">trail_price</code> and <code dir="auto">trail_offset</code> arguments on the following bar to create a trailing stop. The script uses <a href="/pine-script-docs/concepts/lines-and-boxes/#lines">lines</a>, <a href="/pine-script-docs/concepts/text-and-shapes/#labels">labels</a>, and a <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_plot">plot</a> to visualize the trailing stop’s behavior.</p> <p>The green <a href="https://www.tradingview.com/pine-script-reference/v6/#type_line">line</a> on the chart shows the level the market price must reach to activate the trailing stop order. After the price crosses this level, the script uses a blue <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_plot">plot</a> to display the trailing stop’s price. Each time the market price reaches a new high after activating the trailing stop, the stop’s price <em>increases</em> to maintain a distance of <code dir="auto">trailOffsetInput</code> ticks from the best value. The exit order <em>does not</em> change its price level when the market price decreases or does not reach a new high. Eventually, the market price crosses below the trailing stop, triggering an exit:</p> <p><img src="/pine-script-docs/_astro/Strategies-Orders-and-entries-Order-placement-commands-5b.BprhxxcZ_1ujAyE.webp" alt="image" width="1342" height="680" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Trailing stop order demo&quot;, overlay = true, margin_long = 100, margin_short = 100) //@variable The distance from the entry price required to activate the trailing stop. int activationOffsetInput = input.int(1000, &quot;Activation level offset (in ticks)&quot;, 0) //@variable The distance the stop follows behind the highest `high` after activation. int trailOffsetInput = input.int(2000, &quot;Trailing stop offset (in ticks)&quot;, 0) //@variable Draws a label and an optional line at the specified `price`. debugDrawings(float price, string txt, color drawingColor, bool drawLine = false) =&gt; // Draw a label showing the `txt` at the `price` on the current bar. label.new( bar_index, price, text = txt, color = drawingColor, textcolor = color.white, style = label.style_label_lower_right, size = size.large ) // Draw a horizontal line at the `price` starting from the current bar when `drawLine` is `true`. line.new( bar_index, price, bar_index + 1, price, color = drawingColor, extend = extend.right, style = line.style_dashed ) //@variable The level required to activate the trailing stop. var float activationLevel = na //@variable The price of the trailing stop. var float trailingStop = na //@variable The value that the trailing stop would have if it was currently active. float theoreticalStopPrice = high - trailOffsetInput * syminfo.mintick // Place a long market order 100 bars before the last historical bar. if last_bar_index - bar_index == 100 strategy.entry(&quot;Long&quot;, strategy.long) // Create and visualize the exit order on the next bar. if last_bar_index - bar_index == 99 // Update the `activationLevel`. activationLevel := open + syminfo.mintick * activationOffsetInput // Create the trailing stop order that activates at the `activationLevel` and trails behind the `high` by // `trailOffsetInput` ticks. strategy.exit( &quot;Trailing Stop&quot;, from_entry = &quot;Long&quot;, trail_price = activationLevel, trail_offset = trailOffsetInput ) // Create drawings to signify the activation level. debugDrawings(activationLevel, &quot;Trailing Stop Activation Level&quot;, color.green, true) // Visualize the trailing stop&#39;s levels while the position is open. if strategy.opentrades == 1 // Create drawings when the `high` is above the `activationLevel` for the first time to show when the // stop activates. if na(trailingStop) and high &gt; activationLevel debugDrawings(activationLevel, &quot;Activation level crossed&quot;, color.green) trailingStop := theoreticalStopPrice debugDrawings(trailingStop, &quot;Trailing Stop Activated&quot;, color.blue) // Otherwise, update the `trailingStop` value when the `theoreticalStopPrice` reaches a new high. else if theoreticalStopPrice &gt; trailingStop trailingStop := theoreticalStopPrice // Plot the `trailingStop` value to visualize the trailing price movement. plot(trailingStop, &quot;Trailing Stop&quot;)</div> <h4 id="exits-for-multiple-entries" class="md-heading"><a href="#exits-for-multiple-entries">Exits for multiple entries<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h4> <p>A single call to the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> command can generate exit orders for <em>more than one</em> entry in an open position, depending on the call’s <code dir="auto">from_entry</code> value.</p> <p>If an open position consists of two or more entries with the same ID, a single call to <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> with that ID as the <code dir="auto">from_entry</code> argument places exit orders for each corresponding entry created before or on the bar where the call occurs.</p> <p>For example, this script periodically calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> on two consecutive bars to enter and add to a long position. Both calls use “buy” as the <code dir="auto">id</code> argument. After creating the second entry, the script calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> once with “buy” as its <code dir="auto">from_entry</code> argument to generate separate exit orders for each entry with that ID. When the market price reaches the <code dir="auto">takeProfit</code> or <code dir="auto">stopLoss</code> value, the <a href="/pine-script-docs/concepts/strategies/#broker-emulator">broker emulator</a> fills <em>two</em> exit orders and closes the position:</p> <p><img src="/pine-script-docs/_astro/Strategies-Order-placement-and-cancellation-Strategy-exit-Exits-for-multiple-entries-1.C_bGhVv6_nC4KI.webp" alt="image" width="1336" height="500" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Exits for entries with the same ID demo&quot;, overlay = true, pyramiding = 2) //@variable Take-profit price for exit commands. var float takeProfit = na //@variable Stop-loss price for exit commands. var float stopLoss = na //@variable Is `true` on two consecutive bars in 100-bar cycles. bool buyCondition = math.min(bar_index % 100, math.max(bar_index - 1, 0) % 100) == 0 if buyCondition // Place a &quot;buy&quot; market order to enter a trade. strategy.entry(&quot;buy&quot;, strategy.long) // Calculate exits on the second order. if strategy.opentrades == 1 // Update the `takeProfit` and `stopLoss`. takeProfit := close * 1.01 stopLoss := close * 0.99 // Place exit orders for both &quot;buy&quot; entries. strategy.exit(&quot;exit&quot;, &quot;buy&quot;, limit = takeProfit, stop = stopLoss) // Set `takeProfit` and `stopLoss` to `na` when both trades close. if ta.change(strategy.closedtrades) == 2 takeProfit := na stopLoss := na // Plot the `takeProfit` and `stopLoss` values. plot(takeProfit, &quot;TP&quot;, color.green, style = plot.style_circles) plot(stopLoss, &quot;SL&quot;, color.red, style = plot.style_circles)</div> <p>A single <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call can also generate exit orders for <em>all</em> entries in an open position, irrespective of entry ID, when it does not include a <code dir="auto">from_entry</code> argument.</p> <p>Here, we changed the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> instance in the above script to create an entry order with a distinct ID on each call, and we removed the <code dir="auto">from_entry</code> argument from the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call. Since this version does not specify which entries the exit orders apply to, the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call creates orders for <em>every</em> entry in the position:</p> <p><img src="/pine-script-docs/_astro/Strategies-Order-placement-and-cancellation-Strategy-exit-Exits-for-multiple-entries-2.DSQJLM3u_ZFSCp8.webp" alt="image" width="1336" height="500" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Exits for entries with different IDs demo&quot;, overlay = true, pyramiding = 2) //@variable Take-profit price for exit commands. var float takeProfit = na //@variable Stop-loss price for exit commands. var float stopLoss = na //@variable Is `true` on two consecutive bars in 100-bar cycles. bool buyCondition = math.min(bar_index % 100, math.max(bar_index - 1, 0) % 100) == 0 if buyCondition // Place a long market order with a unique ID. strategy.entry(&quot;buy&quot; + str.tostring(strategy.opentrades + strategy.closedtrades), strategy.long) // Calculate exits on the second order. if strategy.opentrades == 1 // Update the `takeProfit` and `stopLoss`. takeProfit := close * 1.01 stopLoss := close * 0.99 // Place exit orders for ALL entries in the position, irrespective of ID. strategy.exit(&quot;exit&quot;, limit = takeProfit, stop = stopLoss) // Set `takeProfit` and `stopLoss` to `na` when both trades close. if ta.change(strategy.closedtrades) == 2 takeProfit := na stopLoss := na // Plot the `takeProfit` and `stopLoss` values. plot(takeProfit, &quot;TP&quot;, color.green, style = plot.style_circles) plot(stopLoss, &quot;SL&quot;, color.red, style = plot.style_circles)</div> <p>It’s crucial to note that a call to <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> without a <code dir="auto">from_entry</code> argument <em>persists</em> and creates exit orders for all open trades in a position, regardless of <em>when</em> the entries occur. This behavior can affect strategies that manage positions with multiple entries or exits. When a strategy has an open position and calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> on any bar without specifying a <code dir="auto">from_entry</code> ID, it generates exit orders for each entry created <em>before</em> or on that bar, and it continues to generate exit orders for subsequent entries <em>after</em> that bar until the position closes.</p> <p>Let’s explore this behavior and how it works. The script below creates a long entry order with <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> on each bar within a user-specified time range, and it calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> without a <code dir="auto">from_entry</code> argument on <em>one bar</em> within that range to generate exit orders for <em>every</em> entry in the open position. The exit command uses a <code dir="auto">loss</code> value of 0, which means an exit order fills each time the market price is not above an entry order’s price.</p> <p>The script prompts users to select three points before it starts its calculations. The first point specifies when order creation begins, the second determines when the single <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call occurs, and the third specifies when order creation stops:</p> <p><img src="/pine-script-docs/_astro/Strategies-Order-placement-and-cancellation-Strategy-exit-Exits-for-multiple-entries-3.BViNenRl_RP72m.webp" alt="image" width="1336" height="530" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Exit persist demo&quot;, overlay = true, margin_long = 100, margin_short = 100, pyramiding = 100) //@variable The time when order creation starts. int entryStartTime = input.time(0, &quot;Start time for entries&quot;, confirm = true) //@variable The time when the `strategy.exit()` call occurs. int exitCallTime = input.time(0, &quot;Exit call time&quot;, confirm = true) //@variable The time when order creation stops. int entryEndTime = input.time(0, &quot;End time for entries&quot;, confirm = true) // Raise a runtime error if incorrect timestamps are chosen. if exitCallTime &lt;= entryStartTime or entryEndTime &lt;= exitCallTime or entryEndTime &lt;= entryStartTime runtime.error(&quot;The input timestamps must follow this condition: entryStartTime &lt; exitCallTime &lt; entryEndTime.&quot;) // Create variables to track entry and exit conditions. bool entriesStart = time == entryStartTime bool callExit = time == exitCallTime bool entriesEnd = time == entryEndTime bool callEntry = time &gt;= entryStartTime and time &lt; entryEndTime // Place a long entry order when `callEntry` is `true`. if callEntry strategy.entry(&quot;Entry&quot;, strategy.long) // Call `strategy.exit()` when `callExit` is `true`, which occurs only once. // This single call persists and creates exit orders for EVERY entry in the position because it does not // specify a `from_entry` ID. if callExit strategy.exit(&quot;Exit&quot;, loss = 0) // Draw labels to signify when entries start, when the `strategy.exit()` call occurs, and when order placement stops. switch entriesStart =&gt; label.new( bar_index, high, &quot;Start placing entry orders.&quot;, color = color.green, textcolor = color.white, style = label.style_label_lower_right, size = size.large ) callExit =&gt; label.new( bar_index, high, &quot;Call `strategy.exit()` once.&quot;, color = color.blue, textcolor = color.white, style = label.style_label_lower_right, size = size.large ) entriesEnd =&gt; label.new( bar_index, high, &quot;Stop placing orders.&quot;, color = color.red, textcolor = color.white, style = label.style_label_lower_left, size = size.large ) // Create a line and label to visualize the lowest entry price, i.e., the price required to close the position. var line lowestLine = line.new( entryStartTime + 1000, na, entryEndTime, na, xloc.bar_time, extend.right, color.orange, width = 2 ) var lowestLabel = label.new( entryStartTime + 1000, na, &quot;Lowest entry price&quot;, color = color.orange, style = label.style_label_upper_right, xloc = xloc.bar_time ) // Update the price values of the `lowestLine` and `lowestLabel` after each new entry. if callEntry[1] var float lowestPrice = strategy.opentrades.entry_price(0) float entryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1) if not na(entryPrice) lowestPrice := math.min(lowestPrice, entryPrice) lowestLine.set_y1(lowestPrice) lowestLine.set_y2(lowestPrice) lowestLabel.set_y(lowestPrice) // Highlight the background when `entriesStart`, `callExit`, and `entriesEnd` occurs. bgcolor(entriesStart ? color.new(color.green, 80) : na, title = &quot;Entries start highlight&quot;) bgcolor(callExit ? color.new(color.blue, 80) : na, title = &quot;Exit call highlight&quot;) bgcolor(entriesEnd ? color.new(color.red, 80) : na, title = &quot;Entries end highlight&quot;)</div> <p>Note that:</p> <ul> <li>We included <code dir="auto">pyramiding = 100</code> in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement, which allows the position to have up to 100 open entries from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a>.</li> <li>The script uses <a href="/pine-script-docs/concepts/text-and-shapes/#labels">labels</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_bgcolor">bgcolor()</a> to signify when order placement starts and stops and when the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call occurs.</li> <li>The script draws a <a href="https://www.tradingview.com/pine-script-reference/v6/#type_line">line</a> and a <a href="https://www.tradingview.com/pine-script-reference/v6/#type_label">label</a> at the lowest <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.opentrades.entry_price">entry price</a> to show the value the market price must reach to close the position.</li> </ul> <p>We can observe the unique <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> behavior in this example by comparing the code itself with the script’s chart outputs. The script calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> <em>one time</em>, only on the bar with the blue <a href="https://www.tradingview.com/pine-script-reference/v6/#type_label">label</a>. However, this single call placed exit orders for every entry <strong>before</strong> or on that bar and continued placing exit orders for all entries <strong>after</strong> that bar. This behavior occurs because <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> has no way to determine when to stop placing orders if it does not link to entries with a specific ID. In this case, the command only ceases to create new exit orders after the position fully closes.</p> <p>The above script would exhibit different behavior if we included a <code dir="auto">from_entry</code> argument in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call. When a call to this command specifies a <code dir="auto">from_entry</code> ID, it only applies to entries with that ID which the strategy created <em>before</em> or <em>on</em> the bar of the call. The command does not place exit orders for subsequent entries created <em>after</em> that bar in that case, even ones with the same ID.</p> <p>Here, we added <code dir="auto">from_entry = &quot;Entry&quot;</code> to our script’s <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call, meaning it only produces exit orders for entries with the “Entry” ID. Only 17 exits occur this time, each corresponding to an entry order created before or on the bar with the blue <a href="https://www.tradingview.com/pine-script-reference/v6/#type_label">label</a>. The call does not affect any entries that the strategy creates <em>after</em> that bar:</p> <p><img src="/pine-script-docs/_astro/Strategies-Order-placement-and-cancellation-Strategy-exit-Exits-for-multiple-entries-4.CErI4zyu_1GDcP4.webp" alt="image" width="1336" height="530" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Exit persist demo&quot;, overlay = true, margin_long = 100, margin_short = 100, pyramiding = 100) //@variable The time when order creation starts. int entryStartTime = input.time(0, &quot;Start time for entries&quot;, confirm = true) //@variable The time when the `strategy.exit()` call occurs. int exitCallTime = input.time(0, &quot;Exit call time&quot;, confirm = true) //@variable The time when order creation stops. int entryEndTime = input.time(0, &quot;End time for entries&quot;, confirm = true) // Raise a runtime error if incorrect timestamps are chosen. if exitCallTime &lt;= entryStartTime or entryEndTime &lt;= exitCallTime or entryEndTime &lt;= entryStartTime runtime.error(&quot;The input timestamps must follow this condition: entryStartTime &lt; exitCallTime &lt; entryEndTime.&quot;) // Create variables to track entry and exit conditions. bool entriesStart = time == entryStartTime bool callExit = time == exitCallTime bool entriesEnd = time == entryEndTime bool callEntry = time &gt;= entryStartTime and time &lt; entryEndTime // Place a long entry order when `callEntry` is `true`. if callEntry strategy.entry(&quot;Entry&quot;, strategy.long) // Call `strategy.exit()` when `callExit` is `true`, which occurs only once. // This single call only places exit orders for all entries with the &quot;Entry&quot; ID created before or on the bar where // `callExit` occurs. It DOES NOT affect any subsequent entries created after that bar. if callExit strategy.exit(&quot;Exit&quot;, from_entry = &quot;Entry&quot;, loss = 0) // Draw labels to signify when entries start, when the `strategy.exit()` call occurs, and when order placement stops. switch entriesStart =&gt; label.new( bar_index, high, &quot;Start placing entry orders.&quot;, color = color.green, textcolor = color.white, style = label.style_label_lower_right, size = size.large ) callExit =&gt; label.new( bar_index, high, &quot;Call `strategy.exit()` once.&quot;, color = color.blue, textcolor = color.white, style = label.style_label_lower_right, size = size.large ) entriesEnd =&gt; label.new( bar_index, high, &quot;Stop placing orders.&quot;, color = color.red, textcolor = color.white, style = label.style_label_lower_left, size = size.large ) // Create a line and label to visualize the lowest entry price, i.e., the price required to close the position. var line lowestLine = line.new( entryStartTime + 1000, na, entryEndTime, na, xloc.bar_time, extend.right, color.orange, width = 2 ) var lowestLabel = label.new( entryStartTime + 1000, na, &quot;Lowest entry price&quot;, color = color.orange, style = label.style_label_upper_right, xloc = xloc.bar_time ) // Update the price values of the `lowestLine` and `lowestLabel` after each new entry. if callEntry[1] var float lowestPrice = strategy.opentrades.entry_price(0) float entryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1) if not na(entryPrice) lowestPrice := math.min(lowestPrice, entryPrice) lowestLine.set_y1(lowestPrice) lowestLine.set_y2(lowestPrice) lowestLabel.set_y(lowestPrice) // Highlight the background when `entriesStart`, `callExit`, and `entriesEnd` occurs. bgcolor(entriesStart ? color.new(color.green, 80) : na, title = &quot;Entries start highlight&quot;) bgcolor(callExit ? color.new(color.blue, 80) : na, title = &quot;Exit call highlight&quot;) bgcolor(entriesEnd ? color.new(color.red, 80) : na, title = &quot;Entries end highlight&quot;)</div> <h3 id="strategyclose-and-strategyclose_all" class="md-heading"><a href="#strategyclose-and-strategyclose_all">`strategy.close()` and `strategy.close_all()`<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close">strategy.close()</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close_all">strategy.close_all()</a> commands generate orders to exit from an open position. Unlike <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a>, which creates <em>price-based</em> exit orders (e.g., <a href="/pine-script-docs/concepts/strategies/#take-profit-and-stop-loss">stop-loss</a>), these commands generate <a href="/pine-script-docs/concepts/strategies/#market-orders">market orders</a> that the <a href="/pine-script-docs/concepts/strategies/#broker-emulator">broker emulator</a> fills on the next available tick, irrespective of the price.</p> <p>The example below demonstrates a simple strategy that places a “buy” entry order with <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> once every 50 bars and a <a href="/pine-script-docs/concepts/strategies/#market-orders">market order</a> to close the long position with <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close">strategy.close()</a> 25 bars afterward:</p> <p><img src="/pine-script-docs/_astro/Strategies-Orders-and-entries-Order-placement-commands-6.C8naMrYK_ZahHab.webp" alt="image" width="1342" height="680" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Close demo&quot;, &quot;test&quot;, overlay = true) //@variable Is `true` on every 50th bar. buyCond = bar_index % 50 == 0 //@variable Is `true` on every 25th bar except for those that are divisible by 50. sellCond = bar_index % 25 == 0 and not buyCond if buyCond strategy.entry(&quot;buy&quot;, strategy.long) if sellCond strategy.close(&quot;buy&quot;) bgcolor(buyCond ? color.new(color.blue, 90) : na) bgcolor(sellCond ? color.new(color.red, 90) : na)</div> <p>Notice that the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close">strategy.close()</a> call in this script uses “buy” as its required <code dir="auto">id</code> argument. Unlike <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a>, this command’s <code dir="auto">id</code> parameter specifies the <em>entry ID</em> of an open trade. It <strong>does not</strong> represent the ID of the resulting exit order. If a market position consists of multiple open trades with the same entry ID, a single <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close">strategy.close()</a> call with that ID as its <code dir="auto">id</code> argument generates a single <a href="/pine-script-docs/concepts/strategies/#market-orders">market order</a> to exit from all of them.</p> <p>The following script creates a “buy” order with <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> once every 25 bars, and it calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close">strategy.close()</a> with “buy” as its <code dir="auto">id</code> argument to close all open trades with that entry ID once every 100 bars. The market order from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close">strategy.close()</a> closes the entire position in this case because every open trade has the same “buy” entry ID:</p> <p><img src="/pine-script-docs/_astro/Strategies-Orders-and-entries-Order-placement-commands-7.BnXt0DwI_2ljg1Q.webp" alt="image" width="1342" height="680" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Multiple close demo&quot;, &quot;test&quot;, overlay = true, pyramiding = 3) //@variable Is `true` on every 100th bar. sellCond = bar_index % 100 == 0 //@variable Is `true` on every 25th bar except for those that are divisible by 100. buyCond = bar_index % 25 == 0 and not sellCond if buyCond strategy.entry(&quot;buy&quot;, strategy.long) if sellCond strategy.close(&quot;buy&quot;) bgcolor(buyCond ? color.new(color.blue, 90) : na) bgcolor(sellCond ? color.new(color.red, 90) : na)</div> <p>Note that:</p> <ul> <li>We included <code dir="auto">pyramiding = 3</code> in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement, allowing the script to generate up to three entries per position with <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> calls.</li> </ul> <p>The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close_all">strategy.close_all()</a> command generates a <a href="/pine-script-docs/concepts/strategies/#market-orders">market order</a> to exit from the open position that <em>does not</em> link to any specific entry ID. This command is helpful when a strategy needs to exit as soon as possible from a position consisting of multiple open trades with different entry IDs.</p> <p>The script below places “A”, “B”, and “C” entry orders sequentially based on the number of <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.opentrades">open trades</a>, and then it calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close_all">strategy.close_all()</a> to create a single order that closes the entire position on the next bar:</p> <p><img src="/pine-script-docs/_astro/Strategies-Orders-and-entries-Order-placement-commands-8.CRIv7OvG_1rGwwH.webp" alt="image" width="1342" height="680" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Close multiple ID demo&quot;, &quot;test&quot;, overlay = true, pyramiding = 3) switch strategy.opentrades 0 =&gt; strategy.entry(&quot;A&quot;, strategy.long) 1 =&gt; strategy.entry(&quot;B&quot;, strategy.long) 2 =&gt; strategy.entry(&quot;C&quot;, strategy.long) 3 =&gt; strategy.close_all()</div> <h3 id="strategycancel-and-strategycancel_all" class="md-heading"><a href="#strategycancel-and-strategycancel_all">`strategy.cancel()` and `strategy.cancel_all()`<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.cancel">strategy.cancel()</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.cancel_all">strategy.cancel_all()</a> commands allow strategies to cancel <em>unfilled</em> orders before the <a href="/pine-script-docs/concepts/strategies/#broker-emulator">broker emulator</a> processes them. These order cancellation commands are most helpful when working with <em>price-based orders</em>, including all orders from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> calls and the orders from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> calls that use <code dir="auto">limit</code> or <code dir="auto">stop</code> arguments.</p> <p>The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.cancel">strategy.cancel()</a> command has a required <code dir="auto">id</code> parameter, which specifies the ID of the entry or exit orders to cancel. The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.cancel_all">strategy.cancel_all()</a> command does not have such a parameter because it cancels <em>all</em> unfilled orders, regardless of ID.</p> <p>The following strategy places a “buy” <a href="/pine-script-docs/concepts/strategies/#limit-orders">limit order</a> 500 ticks below the closing price 100 bars before the last chart bar with <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a>, and it cancels the order on the next bar with <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.cancel">strategy.cancel()</a>. The script highlights the chart’s background to signify when it places and cancels the “buy” order, and it draws a horizontal <a href="https://www.tradingview.com/pine-script-reference/v6/#type_line">line</a> at the order’s price. As we see below, our example chart shows no entry marker when the market price crosses the horizontal line because the strategy already cancels the order (when the chart’s background is orange) before it reaches that level:</p> <p><img src="/pine-script-docs/_astro/Strategies-Orders-and-entries-Order-placement-commands-9.4WRZcmod_TgLp6.webp" alt="image" width="1342" height="680" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Cancel demo&quot;, &quot;test&quot;, overlay = true) //@variable Draws a horizontal line at the `limit` price of the &quot;buy&quot; order. var line limitLine = na //@variable Is `color.green` when the strategy places the &quot;buy&quot; order, `color.orange` when it cancels the order. color bgColor = na if last_bar_index - bar_index == 100 float limitPrice = close - syminfo.mintick * 500 strategy.entry(&quot;buy&quot;, strategy.long, limit = limitPrice) limitLine := line.new(bar_index, limitPrice, bar_index + 1, limitPrice, extend = extend.right) bgColor := color.new(color.green, 50) if last_bar_index - bar_index == 99 strategy.cancel(&quot;buy&quot;) bgColor := color.new(color.orange, 50) bgcolor(bgColor)</div> <p>The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.cancel">strategy.cancel()</a> command affects <em>all</em> unfilled orders with a specified ID. It does nothing if the specified <code dir="auto">id</code> represents the ID of an order that does not exist. When there is more than one unfilled order with the specified ID, the command cancels <em>all</em> of them at once.</p> <p>Below, we’ve modified the previous script to place a “buy” limit order on three consecutive bars, starting 100 bars before the last chart bar. After placing all three orders, the strategy cancels them using <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.cancel">strategy.cancel()</a> with “buy” as the <code dir="auto">id</code> argument, resulting in nothing happening when the market price reaches any of the order prices (horizontal <a href="/pine-script-docs/concepts/lines-and-boxes/#lines">lines</a>):</p> <p><img src="/pine-script-docs/_astro/Strategies-Orders-and-entries-Order-placement-commands-10.BdK1xjss_Z1VR5ov.webp" alt="image" width="1342" height="680" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Multiple cancel demo&quot;, &quot;test&quot;, overlay = true, pyramiding = 3) //@variable Draws a horizontal line at the `limit` price of the &quot;buy&quot; order. var line limitLine = na //@variable Is `color.green` when the strategy places the &quot;buy&quot; order, `color.orange` when it cancels the order. color bgColor = na if last_bar_index - bar_index &lt;= 100 and last_bar_index - bar_index &gt;= 98 float limitPrice = close - syminfo.mintick * 500 strategy.entry(&quot;buy&quot;, strategy.long, limit = limitPrice) limitLine := line.new(bar_index, limitPrice, bar_index + 1, limitPrice, extend = extend.right) bgColor := color.new(color.green, 50) if last_bar_index - bar_index == 97 strategy.cancel(&quot;buy&quot;) bgColor := color.new(color.orange, 50) bgcolor(bgColor)</div> <p>Note that:</p> <ul> <li>We included <code dir="auto">pyramiding = 3</code> in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement, allowing three successive entries from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> per position. The script would also achieve the same result without this setting if it called <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> instead because <a href="/pine-script-docs/concepts/strategies/#pyramiding">pyramiding</a> <em>does not</em> affect orders from that command.</li> </ul> <p>The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.cancel">strategy.cancel()</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.cancel_all">strategy.cancel_all()</a> commands can cancel orders of any type, including <a href="/pine-script-docs/concepts/strategies/#market-orders">market orders</a>. However, it is important to note that either command can cancel a market order only if its call occurs on the <em>same</em> script execution as the order placement command. If the call happens after that point, it has <em>no effect</em> because the <a href="/pine-script-docs/concepts/strategies/#broker-emulator">broker emulator</a> fills market orders on the <em>next available tick</em>.</p> <p>This example places a “buy” market order 100 bars before the last chart bar with <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a>, then it attempts to cancel the order on the next bar with <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.cancel_all">strategy.cancel_all()</a>. The cancellation command <em>does not</em> affect the “buy” order because the broker emulator fills the order on the next bar’s <em>opening tick</em>, which occurs <em>before</em> the script evaluates the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.cancel_all">strategy.cancel_all()</a> call:</p> <p><img src="/pine-script-docs/_astro/Strategies-Orders-and-entries-Order-placement-commands-11.C3U1GI3M_DIxpi.webp" alt="image" width="1342" height="544" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Cancel market demo&quot;, &quot;test&quot;, overlay = true) //@variable Is `color.green` when the strategy places the &quot;buy&quot; order, `color.orange` when it tries to cancel the order. color bgColor = na if last_bar_index - bar_index == 100 strategy.entry(&quot;buy&quot;, strategy.long) bgColor := color.new(color.green, 50) if last_bar_index - bar_index == 99 strategy.cancel_all() bgColor := color.new(color.orange, 50) bgcolor(bgColor)</div> <h2 id="position-sizing" class="md-heading"><a href="#position-sizing">Position sizing<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p>Pine Script™ strategies feature two ways to control the sizes of the orders that open and manage positions:</p> <ul> <li>Set a default <em>fixed</em> quantity type and value for the orders. Programmers can specify defaults for these properties by including <code dir="auto">default_qty_type</code> and <code dir="auto">default_qty_value</code> arguments in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement. Script users can adjust these values with the “Order size” inputs in the “Settings/Properties” tab.</li> <li>Include a <em>non-na</em> <code dir="auto">qty</code> argument in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> or <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> call. When a call to either of these commands specifies a non-na <code dir="auto">qty</code> value, that call ignores the strategy’s default quantity type and value and places an order for <code dir="auto">qty</code> contracts/shares/lots/units instead.</li> </ul> <p>The following example uses <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> calls with different <code dir="auto">qty</code> values for long and short trades. When the current bar’s <a href="https://www.tradingview.com/pine-script-reference/v6/#var_low">low</a> equals the <code dir="auto">lowest</code> value, the script places a “Buy” order to enter a long position of <code dir="auto">longAmount</code> units. Otherwise, when the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_high">high</a> equals the <code dir="auto">highest</code> value, it places a “Sell” order to enter a short position of <code dir="auto">shortAmount</code> units:</p> <p><img src="/pine-script-docs/_astro/Strategies-Position-sizing-1.CpMYvl8Y_ZCp8n6.webp" alt="image" width="1342" height="740" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Buy low, sell high&quot;, overlay = true, default_qty_type = strategy.cash, default_qty_value = 5000) int length = input.int(20, &quot;Length&quot;, 1) float longAmount = input.float(4.0, &quot;Long Amount&quot;, 0.0) float shortAmount = input.float(2.0, &quot;Short Amount&quot;, 0.0) float highest = ta.highest(length) float lowest = ta.lowest(length) switch low == lowest =&gt; strategy.entry(&quot;Buy&quot;, strategy.long, longAmount) high == highest =&gt; strategy.entry(&quot;Sell&quot;, strategy.short, shortAmount)</div> <p>Notice that although we’ve included <code dir="auto">default_qty_type</code> and <code dir="auto">default_qty_value</code> arguments in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement, the strategy <em>does not</em> use this default setting to size its orders because the specified <code dir="auto">qty</code> in the entry commands takes precedence. If we want to use the default size, we must <em>remove</em> the <code dir="auto">qty</code> arguments from the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> calls or set their values to <a href="https://www.tradingview.com/pine-script-reference/v6/#var_na">na</a>.</p> <p>Here, we edited the previous script by including <a href="/pine-script-docs/language/operators/#-ternary-operator">ternary</a> expressions for the <code dir="auto">qty</code> arguments in both <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> calls that replace input values of 0 with <a href="https://www.tradingview.com/pine-script-reference/v6/#var_na">na</a>. If the specified <code dir="auto">longAmount</code> or <code dir="auto">shortAmount</code> is 0, which is what we set as the new default, the corresponding entry orders use the strategy’s default order size instead, as we see below:</p> <p><img src="/pine-script-docs/_astro/Strategies-Position-sizing-2.BNMrWxCG_Z1eMhKJ.webp" alt="image" width="1342" height="740" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Buy low, sell high&quot;, overlay = true, default_qty_type = strategy.cash, default_qty_value = 5000) int length = input.int(20, &quot;Length&quot;, 1) float longAmount = input.float(0.0, &quot;Long Amount&quot;, 0.0) float shortAmount = input.float(0.0, &quot;Short Amount&quot;, 0.0) float highest = ta.highest(length) float lowest = ta.lowest(length) switch low == lowest =&gt; strategy.entry(&quot;Buy&quot;, strategy.long, longAmount == 0.0 ? na : longAmount) high == highest =&gt; strategy.entry(&quot;Sell&quot;, strategy.short, shortAmount == 0.0 ? na : shortAmount)</div> <h2 id="closing-a-market-position" class="md-heading"><a href="#closing-a-market-position">Closing a market position<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p>By default, strategies close a market position using the <em>First In, First Out (FIFO)</em> method, which means that any exit order closes or reduces the position starting with the <em>first</em> open trade, even if the exit command specifies the entry ID of a <em>different</em> open trade. To override this default behavior, include <code dir="auto">close_entries_rule = &quot;ANY&quot;</code> in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement.</p> <p>The following example places “Buy1” and “Buy2” entry orders sequentially, starting 100 bars before the latest chart bar. When the position size is 0, it calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> to place the “Buy1” order for five units. After the strategy’s position size matches the size of that order, it uses <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> to place the “Buy2” order for ten units. The strategy then creates “bracket” exit orders <a href="/pine-script-docs/concepts/strategies/#exits-for-multiple-entries">for both entries</a> using a single <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call without a <code dir="auto">from_entry</code> argument. For visual reference, the script plots the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.position_size">strategy.position_size</a> value in a separate pane:</p> <p><img src="/pine-script-docs/_astro/Strategies-Closing-a-market-position-1.CG44yAVx_1GNd4G.webp" alt="image" width="1342" height="686" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Exit Demo&quot;, pyramiding = 2) float positionSize = strategy.position_size if positionSize == 0 and last_bar_index - bar_index &lt;= 100 strategy.entry(&quot;Buy1&quot;, strategy.long, 5) else if positionSize == 5 strategy.entry(&quot;Buy2&quot;, strategy.long, 10) else if positionSize == 15 strategy.exit(&quot;bracket&quot;, loss = 10, profit = 10) plot(positionSize == 0 ? na : positionSize, &quot;Position Size&quot;, color.lime, 4, plot.style_histogram)</div> <p>Note that:</p> <ul> <li>We included <code dir="auto">pyramiding = 2</code> in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement, allowing two successive entries from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> per position.</li> </ul> <p>Each time the market price triggers an exit order, the above script exits from the open position, starting with the <em>oldest</em> open trade. This FIFO behavior applies even if we explicitly specify an exit from “Buy2” before “Buy1” in the code.</p> <p>The script version below calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close">strategy.close()</a> with “Buy2” as its <code dir="auto">id</code> argument, and it includes “Buy1” as the <code dir="auto">from_entry</code> argument in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call. The <a href="/pine-script-docs/concepts/strategies/#market-orders">market order</a> from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close">strategy.close()</a> executes on the next available tick, meaning the <a href="/pine-script-docs/concepts/strategies/#broker-emulator">broker emulator</a> fills it <em>before</em> the <a href="/pine-script-docs/concepts/strategies/#take-profit-and-stop-loss">take-profit</a> and <a href="/pine-script-docs/concepts/strategies/#take-profit-and-stop-loss">stop-loss</a> orders from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a>:</p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Exit Demo&quot;, pyramiding = 2) float positionSize = strategy.position_size if positionSize == 0 and last_bar_index - bar_index &lt;= 100 strategy.entry(&quot;Buy1&quot;, strategy.long, 5) else if positionSize == 5 strategy.entry(&quot;Buy2&quot;, strategy.long, 10) else if positionSize == 15 strategy.close(&quot;Buy2&quot;) strategy.exit(&quot;bracket&quot;, &quot;Buy1&quot;, loss = 10, profit = 10) plot(positionSize == 0 ? na : positionSize, &quot;Position Size&quot;, color.lime, 4, plot.style_histogram)</div> <p>The market order from the script’s <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close">strategy.close()</a> call is for 10 units because it links to the open trade with the “Buy2” entry ID. A user might expect this strategy to close that trade completely when the order executes. However, the “List of Trades” tab shows that five units of the order go toward closing the “Buy1” trade <em>first</em> because it is the oldest, and the remaining five units close <em>half</em> of the “Buy2” trade. After that, the “bracket” orders from the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call close the rest of the position:</p> <p><img src="/pine-script-docs/_astro/Strategies-Closing-a-market-position-2.tTsJ7OdZ_Z2rHJes.webp" alt="image" width="1342" height="518" loading="lazy" decoding="async"></p> <p>Note that:</p> <ul> <li>If we included <code dir="auto">close_entries_rule = &quot;ANY&quot;</code> in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement, the market order from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close">strategy.close()</a> would close the open trade with the “Buy2” entry ID <em>first</em>, and then the “bracket” orders from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> would close the trade with the “Buy1” entry ID.</li> </ul> <h2 id="oca-groups" class="md-heading"><a href="#oca-groups">OCA groups<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p><em>One-Cancels-All (OCA)</em> groups allow a strategy to fully or partially <em>cancel</em> specific orders when the <a href="/pine-script-docs/concepts/strategies/#broker-emulator">broker emulator</a> executes another order from the same group. To assign an order to an OCA group, include an <code dir="auto">oca_name</code> argument in the call to the <a href="/pine-script-docs/concepts/strategies/#order-placement-and-cancellation">order placement command</a>. The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> commands also allow programmers to specify an <em>OCA type</em>, which defines whether a strategy <a href="/pine-script-docs/concepts/strategies/#strategyocacancel">cancels</a>, <a href="/pine-script-docs/concepts/strategies#strategyocareduce">reduces</a>, or <a href="/pine-script-docs/concepts/strategies#strategyocanone">does not modify</a> the order after executing other orders.</p> <aside aria-label="Notice!" class="tv-informer not-content" style="--informer-header-color:#FF9800;--informer-back-color-light:#FFF3E0;--informer-back-color-dark:#33261A"><div class="tv-informer-icon"><svg viewBox="0 0 18 18" width="18" height="18"><path fill-rule="evenodd" d="M9 17A8 8 0 1 0 9 1a8 8 0 0 0 0 16ZM9 4c-.79 0-1.38.7-1.25 1.48l.67 4.03a.59.59 0 0 0 1.16 0l.67-4.03A1.27 1.27 0 0 0 9 4Zm0 8a1 1 0 1 0 0 2 1 1 0 0 0 0-2Z" fill="currentColor"></path></svg></div><div class="tv-informer-content"><p><span class="tv-informer-header">Notice!</span>All order placement commands that issue orders for the same OCA group must specify the same group name <strong>and</strong> OCA type. If two commands have the same <code dir="auto">oca_name</code> but <em>different</em> <code dir="auto">oca_type</code> values, the strategy considers them to be from <strong>two distinct groups</strong>. In other words, an OCA group <strong>cannot</strong> mix the <a href="https://www.tradingview.com/pine-script-reference/v6/#const_strategy.oca.cancel">strategy.oca.cancel</a>, <a href="https://www.tradingview.com/pine-script-reference/v6/#const_strategy.oca.reduce">strategy.oca.reduce</a>, and <a href="https://www.tradingview.com/pine-script-reference/v6/#const_strategy.oca.none">strategy.oca.none</a> OCA types.</p></div></aside> <h3 id="strategyocacancel" class="md-heading"><a href="#strategyocacancel">`strategy.oca.cancel`<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>When an order placement command uses <a href="https://www.tradingview.com/pine-script-reference/v6/#const_strategy.oca.cancel">strategy.oca.cancel</a> as its <code dir="auto">oca_type</code> argument, the strategy completely <em>cancels</em> the resulting order if another order from the same OCA group executes first.</p> <p>To demonstrate how this OCA type impacts a strategy’s orders, consider the following script, which places orders when the <code dir="auto">ma1</code> value crosses the <code dir="auto">ma2</code> value. If the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.position_size">strategy.position_size</a> is 0 when the cross occurs, the strategy places two <a href="/pine-script-docs/concepts/strategies/#stop-and-stop-limit-orders">stop orders</a> with <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> calls. The first is a long order at the bar’s <a href="https://www.tradingview.com/pine-script-reference/v6/#var_high">high</a>, and the second is a short order at the bar’s <a href="https://www.tradingview.com/pine-script-reference/v6/#var_low">low</a>. If the strategy already has an open position during the cross, it calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close_all">strategy.close_all()</a> to close the position with a <a href="/pine-script-docs/concepts/strategies/#market-orders">market order</a>:</p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;OCA Cancel Demo&quot;, overlay=true) float ma1 = ta.sma(close, 5) float ma2 = ta.sma(close, 9) if ta.cross(ma1, ma2) if strategy.position_size == 0 strategy.order(&quot;Long&quot;, strategy.long, stop = high) strategy.order(&quot;Short&quot;, strategy.short, stop = low) else strategy.close_all() plot(ma1, &quot;Fast MA&quot;, color.aqua) plot(ma2, &quot;Slow MA&quot;, color.orange)</div> <p>Depending on the price action, the strategy might fill <em>both</em> stop orders before creating the closing market order. In that case, the strategy exits the position without evaluating <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close_all">strategy.close_all()</a> because both orders have the same size. We see this behavior in the chart below, where the strategy alternated between executing “Long” and “Short” orders a few times without executing an order from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close_all">strategy.close_all()</a>:</p> <p><img src="/pine-script-docs/_astro/Strategies-OCA-groups-Strategy-oca-cancel-1.B4pkrsRw_1KFx5x.webp" alt="image" width="1816" height="550" loading="lazy" decoding="async"></p> <p>To eliminate scenarios where the strategy fills the “Long” and “Short” orders before evaluating the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close_all">strategy.close_all()</a> call, we can instruct it to <em>cancel</em> one of the orders after it executes the other. Below, we included “Entry” as the <code dir="auto">oca_name</code> argument and <a href="https://www.tradingview.com/pine-script-reference/v6/#const_strategy.oca.cancel">strategy.oca.cancel</a> as the <code dir="auto">oca_type</code> argument in both <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> calls. Now, after the strategy executes either the “Long” or “Short” order, it cancels the other order and waits for <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close_all">strategy.close_all()</a> to close the position:</p> <p><img src="/pine-script-docs/_astro/Strategies-OCA-groups-Strategy-oca-cancel-2.Pw0HBDfm_ZLEEMG.webp" alt="image" width="1816" height="550" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;OCA Cancel Demo&quot;, overlay=true) float ma1 = ta.sma(close, 5) float ma2 = ta.sma(close, 9) if ta.cross(ma1, ma2) if strategy.position_size == 0 strategy.order(&quot;Long&quot;, strategy.long, stop = high, oca_name = &quot;Entry&quot;, oca_type = strategy.oca.cancel) strategy.order(&quot;Short&quot;, strategy.short, stop = low, oca_name = &quot;Entry&quot;, oca_type = strategy.oca.cancel) else strategy.close_all() plot(ma1, &quot;Fast MA&quot;, color.aqua) plot(ma2, &quot;Slow MA&quot;, color.orange)</div> <h3 id="strategyocareduce" class="md-heading"><a href="#strategyocareduce">`strategy.oca.reduce`<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>When an order placement command uses <a href="https://www.tradingview.com/pine-script-reference/v6/#const_strategy.oca.reduce">strategy.oca.reduce</a> as its OCA type, the strategy <em>does not</em> cancel the resulting order entirely if another order with the same OCA name executes first. Instead, it <em>reduces</em> the order’s size by the filled number of contracts/shares/lots/units, which is particularly useful for custom exit strategies.</p> <p>The following example demonstrates a <em>long-only</em> strategy that generates a single stop-loss order and two take-profit orders for each new entry. When a faster moving average crosses over a slower one, the script calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> with <code dir="auto">qty = 6</code> to create an entry order, and then it uses three <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> calls to create a <a href="/pine-script-docs/concepts/strategies/#stop-and-stop-limit-orders">stop order</a> at the <code dir="auto">stop</code> price and two <a href="/pine-script-docs/concepts/strategies/#limit-orders">limit orders</a> at the <code dir="auto">limit1</code> and <code dir="auto">limit2</code> prices. The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> call for the “Stop” order uses <code dir="auto">qty = 6</code>, and the two calls for the “Limit 1” and “Limit 2” orders both use <code dir="auto">qty = 3</code>:</p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Multiple TP Demo&quot;, overlay = true) var float stop = na var float limit1 = na var float limit2 = na bool longCondition = ta.crossover(ta.sma(close, 5), ta.sma(close, 9)) if longCondition and strategy.position_size == 0 stop := close * 0.99 limit1 := close * 1.01 limit2 := close * 1.02 strategy.entry(&quot;Long&quot;, strategy.long, 6) strategy.order(&quot;Stop&quot;, strategy.short, stop = stop, qty = 6) strategy.order(&quot;Limit 1&quot;, strategy.short, limit = limit1, qty = 3) strategy.order(&quot;Limit 2&quot;, strategy.short, limit = limit2, qty = 3) bool showPlot = strategy.position_size != 0 plot(showPlot ? stop : na, &quot;Stop&quot;, color.red, style = plot.style_linebr) plot(showPlot ? limit1 : na, &quot;Limit 1&quot;, color.green, style = plot.style_linebr) plot(showPlot ? limit2 : na, &quot;Limit 2&quot;, color.green, style = plot.style_linebr)</div> <p>After adding this strategy to the chart, we see it does not work as initially intended. The problem with this script is that the orders from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> <strong>do not</strong> belong to an OCA group by default (unlike <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a>, whose orders automatically belong to a <a href="https://www.tradingview.com/pine-script-reference/v6/#const_strategy.oca.reduce">strategy.oca.reduce</a> OCA group). Since the strategy does not assign the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> calls to any OCA group, it does not reduce any unfilled stop or limit orders after executing an order. Consequently, if the <a href="/pine-script-docs/concepts/strategies/#broker-emulator">broker emulator</a> fills the stop order and at least one of the limit orders, the traded quantity <strong>exceeds</strong> the open long position, resulting in an open <em>short</em> position:</p> <p><img src="/pine-script-docs/_astro/Strategies-OCA-groups-Strategy-oca-reduce-1.B8XPX6-M_ZmN4JH.webp" alt="image" width="1818" height="830" loading="lazy" decoding="async"></p> <p>For our long-only strategy to work as we intended, we must instruct it to <em>reduce</em> the sizes of the unfilled stop/limit orders after one of them executes to prevent selling a larger quantity than the open long position.</p> <p>Below, we specified “Bracket” as the <code dir="auto">oca_name</code> and <a href="https://www.tradingview.com/pine-script-reference/v6/#const_strategy.oca.reduce">strategy.oca.reduce</a> as the <code dir="auto">oca_type</code> in all the script’s <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> calls. These changes tell the strategy to reduce the sizes of the orders in the “Bracket” group each time the broker emulator fills one of them. This version of the strategy never simulates a short position because the total size of its filled stop and limit orders never <em>exceeds</em> the long position’s size:</p> <p><img src="/pine-script-docs/_astro/Strategies-OCA-groups-Strategy-oca-reduce-2.C2FZumhg_1kQ60w.webp" alt="image" width="1818" height="664" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Multiple TP Demo&quot;, overlay = true) var float stop = na var float limit1 = na var float limit2 = na bool longCondition = ta.crossover(ta.sma(close, 5), ta.sma(close, 9)) if longCondition and strategy.position_size == 0 stop := close * 0.99 limit1 := close * 1.01 limit2 := close * 1.02 strategy.entry(&quot;Long&quot;, strategy.long, 6) strategy.order(&quot;Stop&quot;, strategy.short, stop = stop, qty = 6, oca_name = &quot;Bracket&quot;, oca_type = strategy.oca.reduce) strategy.order(&quot;Limit 1&quot;, strategy.short, limit = limit1, qty = 3, oca_name = &quot;Bracket&quot;, oca_type = strategy.oca.reduce) strategy.order(&quot;Limit 2&quot;, strategy.short, limit = limit2, qty = 6, oca_name = &quot;Bracket&quot;, oca_type = strategy.oca.reduce) bool showPlot = strategy.position_size != 0 plot(showPlot ? stop : na, &quot;Stop&quot;, color.red, style = plot.style_linebr) plot(showPlot ? limit1 : na, &quot;Limit 1&quot;, color.green, style = plot.style_linebr) plot(showPlot ? limit2 : na, &quot;Limit 2&quot;, color.green, style = plot.style_linebr)</div> <p>Note that:</p> <ul> <li>We also changed the <code dir="auto">qty</code> value of the “Limit 2” order to 6 instead of 3 because the strategy reduces its amount by three units when it executes the “Limit 1” order. Keeping the <code dir="auto">qty</code> value of 3 would cause the second limit order’s size to drop to 0 after the strategy fills the first limit order, meaning it would never execute.</li> </ul> <h3 id="strategyocanone" class="md-heading"><a href="#strategyocanone">`strategy.oca.none`<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>When an order placement command uses <a href="https://www.tradingview.com/pine-script-reference/v6/#const_strategy.oca.none">strategy.oca.none</a> as its <code dir="auto">oca_type</code> value, all orders from that command execute <em>independently</em> of any OCA group. This value is the default <code dir="auto">oca_type</code> for the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.order">strategy.order()</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> commands.</p> <h2 id="currency" class="md-heading"><a href="#currency">Currency<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p>Pine Script™ strategies can use different currencies in their calculations than the instruments they simulate trades on. Programmers can specify a strategy’s <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.account_currency">account currency</a> by including a <code dir="auto">currency.*</code> variable as the <code dir="auto">currency</code> argument in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement. The default value is <a href="https://www.tradingview.com/pine-script-reference/v6/#const_currency.NONE">currency.NONE</a>, meaning the strategy uses the same currency as the current chart (<a href="https://www.tradingview.com/pine-script-reference/v6/#var_syminfo.currency">syminfo.currency</a>). Script users can change the account currency using the “Base currency” input in the script’s “Settings/Properties” tab.</p> <p>When a strategy script uses an account currency that differs from the chart’s currency, it uses the <em>previous daily value</em> of a corresponding currency pair from the most popular exchange to determine the conversion rate. If no exchange provides the rate directly, it derives the rate using a <a href="https://www.tradingview.com/support/solutions/43000502298-spread-charts/">spread symbol</a>. The strategy multiplies all monetary values, including simulated profits/losses, by the determined cross rate to express them in the account currency. To retrieve the rate that a strategy uses to convert monetary values, call <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_request.currency_rate">request.currency_rate()</a> with <a href="https://www.tradingview.com/pine-script-reference/v6/#var_syminfo.currency">syminfo.currency</a> as the <code dir="auto">from</code> argument and <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.account_currency">strategy.account_currency</a> as the <code dir="auto">to</code> argument.</p> <p>Note that:</p> <ul> <li>Programmers can directly convert values expressed in a strategy’s account currency to the chart’s currency and vice versa via the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.convert_to_symbol">strategy.convert_to_symbol()</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.convert_to_account">strategy.convert_to_account()</a> functions.</li> </ul> <p>The following example demonstrates how currency conversion affects a strategy’s monetary values and how a strategy’s cross-rate calculations match those that <code dir="auto">request.*()</code> functions use.</p> <p>On each of the latest 500 bars, the strategy places an entry order with <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a>, and it places a <a href="/pine-script-docs/concepts/strategies/#take-profit-and-stop-loss">take-profit</a> and <a href="/pine-script-docs/concepts/strategies/#take-profit-and-stop-loss">stop-loss</a> order one tick away from the entry price with <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a>. The size of each entry order is <code dir="auto">1.0 / syminfo.mintick</code>, rounded to the nearest tick, which means that the profit/loss of each closed trade is equal to <em>one point</em> in the chart’s <em>quote currency</em>. We specified <a href="https://www.tradingview.com/pine-script-reference/v6/#const_currency.EUR">currency.EUR</a> as the account currency in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement, meaning the strategy multiplies all monetary values by a cross rate to express them in Euros.</p> <p>The script calculates the absolute change in the ratio of the strategy’s <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.netprofit">net profit</a> to the symbol’s <a href="https://www.tradingview.com/pine-script-reference/v6/#var_syminfo.pointvalue">point value</a> to determine the value of <em>one unit</em> of the chart’s currency in Euros. It plots this value alongside the result from a <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_request.currency_rate">request.currency_rate()</a> call that uses <a href="https://www.tradingview.com/pine-script-reference/v6/#var_syminfo.currency">syminfo.currency</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.account_currency">strategy.account_currency</a> as the <code dir="auto">from</code> and <code dir="auto">to</code> arguments. As we see below, both plots align, confirming that strategies and <code dir="auto">request.*()</code> functions use the <em>same</em> daily cross-rate calculations:</p> <p><img src="/pine-script-docs/_astro/Strategies-Currency-1.BIrX-27H_1pt4ls.webp" alt="image" width="1820" height="718" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Currency Test&quot;, currency = currency.EUR) if last_bar_index - bar_index &lt; 500 // Place an entry order with a size that results in a P/L of `syminfo.pointvalue` units of chart currency per tick. strategy.entry(&quot;LE&quot;, strategy.long, math.round_to_mintick(1.0 / syminfo.mintick)) // Place exit orders one tick above and below the &quot;LE&quot; entry price, // meaning each trade closes with one point of profit or loss in the chart&#39;s currency. strategy.exit(&quot;LX&quot;, &quot;LE&quot;, profit = 1, loss = 1) // Plot the absolute change in `strategy.netprofit / syminfo.pointvalue`, which represents 1 chart unit of profit/loss. plot( math.abs(ta.change(strategy.netprofit / syminfo.pointvalue)), &quot;1 chart unit of profit/loss in EUR&quot;, color = color.fuchsia, linewidth = 4 ) // Plot the requested currency rate. plot(request.currency_rate(syminfo.currency, strategy.account_currency), &quot;Requested conversion rate&quot;, color.lime)</div> <p>Note that:</p> <ul> <li>When a strategy executes on a chart with a timeframe higher than “1D”, it uses the data from <em>one day before</em> each <em>historical</em> bar’s closing time for its cross-rate calculations. For example, on a “1W” chart, the strategy bases its cross rate on the previous Thursday’s closing values. However, it still uses the latest confirmed daily rate on <em>realtime</em> bars.</li> </ul> <h2 id="altering-calculation-behavior" class="md-heading"><a href="#altering-calculation-behavior">Altering calculation behavior<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p>Strategy scripts execute across all available historical chart bars and continue to execute on realtime bars as new data comes in. However, by default, strategies only recalculate their values after a bar <em>closes</em>, even on realtime bars, and the earliest point that the <a href="/pine-script-docs/concepts/strategies/#broker-emulator">broker emulator</a> fills the orders a strategy places on the close one bar is at the <em>open</em> of the following bar.</p> <p>Users can change these behaviors with the <code dir="auto">calc_on_every_tick</code>, <code dir="auto">calc_on_order_fills</code>, and <code dir="auto">process_orders_on_close</code> parameters of the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement or the corresponding inputs in the “Recalculate” and “Fill orders” sections of the script’s “Settings/Properties” tab. The sections below explain how these settings affect a strategy’s calculations.</p> <h3 id="calc_on_every_tick" class="md-heading"><a href="#calc_on_every_tick">`calc_on_every_tick`<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>The <code dir="auto">calc_on_every_tick</code> parameter of the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> function determines the frequency of a strategy’s calculations on <em>realtime bars</em>. When this parameter’s value is <code dir="auto">true</code>, the script recalculates on each <em>new tick</em> in the realtime data feed. Its default value is <code dir="auto">false</code>, meaning the script only executes on a realtime bar after it closes. Users can also toggle this recalculation behavior with the “On every tick” input in the script’s “Settings/Properties” tab.</p> <p>Enabling this setting can be useful in forward testing because it allows a strategy to use realtime price updates in its calculations. However, it <em>does not</em> affect the calculations on historical bars because historical data feeds <em>do not</em> contain complete tick data: the broker emulator considers each historical bar to have only four ticks (open, high, low, and close). Therefore, users should exercise caution and understand the limitations of this setting. If enabling calculation on every tick causes a strategy to behave <em>differently</em> on historical and realtime bars, the strategy will <strong><a href="/pine-script-docs/concepts/repainting/">repaint</a></strong> after the user reloads it.</p> <p>The following example demonstrates how recalculation on every tick can cause strategy repainting. The script uses <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> calls to place a long entry order each time the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_close">close</a> reaches its <code dir="auto">highest</code> value and a short entry order each time the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_close">close</a> reaches its <code dir="auto">lowest</code> value. The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement includes <code dir="auto">calc_on_every_tick = true</code>, meaning that on realtime bars, it can recalculate and place orders on new price updates <em>before</em> a bar closes:</p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Donchian Channel Break&quot;, overlay = true, calc_on_every_tick = true, pyramiding = 20) int length = input.int(15, &quot;Length&quot;) float highest = ta.highest(close, length) float lowest = ta.lowest(close, length) if close == highest strategy.entry(&quot;Buy&quot;, strategy.long) if close == lowest strategy.entry(&quot;Sell&quot;, strategy.short) // Highlight the background of realtime bars. bgcolor(barstate.isrealtime ? color.new(color.orange, 80) : na) plot(highest, &quot;Highest&quot;, color = color.lime) plot(lowest, &quot;Lowest&quot;, color = color.red)</div> <p>Note that:</p> <ul> <li>The script uses a <a href="/pine-script-docs/concepts/strategies/#pyramiding">pyramiding</a> value of 20, allowing it to simulate up to 20 entries per position with the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> command.</li> <li>The script highlights the chart’s background orange when <a href="https://www.tradingview.com/pine-script-reference/v6/#var_barstate.isrealtime">barstate.isrealtime</a> is <code dir="auto">true</code> to indicate realtime bars.</li> </ul> <p>After applying the script to our chart and letting it run on several realtime bars, we see the following output:</p> <p><img src="/pine-script-docs/_astro/Strategies-Altering-calculation-behavior-Calc-on-every-tick-1.BX0Fex4v_2vXWeQ.webp" alt="image" width="1820" height="842" loading="lazy" decoding="async"></p> <p>The script placed a “Buy” order on <em>each tick</em> where the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_close">close</a> was at the <code dir="auto">highest</code> value, which happened <em>more than once</em> on each realtime bar. Additionally, the <a href="/pine-script-docs/concepts/strategies/#broker-emulator">broker emulator</a> filled each <a href="/pine-script-docs/concepts/strategies/#market-orders">market order</a> at the current realtime price rather than strictly at the open of the following chart bar.</p> <p>After we reload the chart, we see that the strategy <em>changed</em> its behavior and <em>repainted</em> its results on those bars. This time, the strategy placed only <em>one</em> “Buy” order for each <em>closed bar</em> where the condition was valid, and the broker emulator filled each order at the open of the following bar. It did not generate multiple entries per bar because what were previously realtime bars became <em>historical</em> bars, which <strong>do not</strong> hold complete tick data:</p> <p><img src="/pine-script-docs/_astro/Strategies-Altering-calculation-behavior-Calc-on-every-tick-2.CEEZdx06_1CeGHx.webp" alt="image" width="1820" height="842" loading="lazy" decoding="async"></p> <h3 id="calc_on_order_fills" class="md-heading"><a href="#calc_on_order_fills">`calc_on_order_fills`<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>The <code dir="auto">calc_on_order_fills</code> parameter of the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> function enables a strategy to recalculate immediately after an <em>order fills</em>, allowing it to use more granular information and place additional orders without waiting for a bar to close. Its default value is <code dir="auto">false</code>, meaning the strategy does not allow recalculation immediately after every order fill. Users can also toggle this behavior with the “After order is filled” input in the script’s “Settings/Properties” tab.</p> <p>Enabling this setting can provide a strategy script with additional data that would otherwise not be available until after a bar closes, such as the current average price of a simulated position on an open bar.</p> <p>The example below shows a simple strategy that creates a “Buy” order with <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> whenever the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.position_size">strategy.position_size</a> is 0. The script uses <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.position_avg_price">strategy.position_avg_price</a> to calculate price levels for the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> call’s stop-loss and take-profit orders that close the position.</p> <p>We’ve included <code dir="auto">calc_on_order_fills = true</code> in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement, meaning that the strategy recalculates each time the <a href="/pine-script-docs/concepts/strategies/#broker-emulator">broker emulator</a> fills a “Buy” or “Exit” order. Each time an “Exit” order fills, the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.position_size">strategy.position_size</a> reverts to 0, triggering a new “Buy” order. The broker emulator fills the “Buy” order on the next tick at one of the bar’s OHLC values, and then the strategy uses the recalculated <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.position_avg_price">strategy.position_avg_price</a> value to determine new “Exit” order prices:</p> <p><img src="/pine-script-docs/_astro/Strategies-Altering-calculation-behavior-Calc-on-order-fills-1.TfUCX8p2_7gwAM.webp" alt="image" width="1820" height="842" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Intrabar exit&quot;, overlay = true, calc_on_order_fills = true) float stopSize = input.float(5.0, &quot;SL %&quot;, minval = 0.0) / 100.0 float profitSize = input.float(5.0, &quot;TP %&quot;, minval = 0.0) / 100.0 if strategy.position_size == 0.0 strategy.entry(&quot;Buy&quot;, strategy.long) float stopLoss = strategy.position_avg_price * (1.0 - stopSize) float takeProfit = strategy.position_avg_price * (1.0 + profitSize) strategy.exit(&quot;Exit&quot;, stop = stopLoss, limit = takeProfit)</div> <p>Note that:</p> <ul> <li>Without enabling recalculation on order fills, this strategy would not place new orders <em>before</em> a bar closes. After an exit, the strategy would wait for the bar to close before placing a new “Buy” order, which the broker emulator would fill on the <em>next tick</em> after that, i.e., the open of the following bar.</li> </ul> <p>It’s important to note that enabling <code dir="auto">calc_on_order_fills</code> can produce unrealistic strategy results in some cases because the <a href="/pine-script-docs/concepts/strategies/#broker-emulator">broker emulator</a> may assume order-fill prices that are <em>not</em> obtainable in real-world trading. Therefore, users should exercise caution and carefully examine their strategy logic when allowing recalculation on order fills.</p> <p>For example, the following script places a “Buy” order after each new order fill and bar close over the most recent 25 historical bars. The strategy simulates <em>four</em> entries per bar because the broker emulator considers each historical bar to have <em>four ticks</em> (open, high, low, and close). This behavior is unrealistic because it is not typically possible to fill an order at a bar’s <em>exact</em> high or low price:</p> <p><img src="/pine-script-docs/_astro/Strategies-Altering-calculation-behavior-Calc-on-order-fills-2.vGEDeBsL_1sBc2Q.webp" alt="image" width="1818" height="506" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;buy on every fill&quot;, overlay = true, calc_on_order_fills = true, pyramiding = 100) if last_bar_index - bar_index &lt;= 25 strategy.entry(&quot;Buy&quot;, strategy.long)</div> <h3 id="process_orders_on_close" class="md-heading"><a href="#process_orders_on_close">`process_orders_on_close`<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>By default, strategies simulate orders at the close of each bar, meaning that the earliest opportunity to fill the orders and execute strategy calculations and alerts is on the opening of the following bar. Programmers can change this behavior to process orders on the <em>closing tick</em> of each bar by setting <code dir="auto">process_orders_on_close</code> to <code dir="auto">true</code> in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement. Users can set this behavior by changing the “Fill Orders/On Bar Close” setting in the “Settings/Properties” tab.</p> <p>This behavior is most useful when backtesting manual strategies in which traders exit from a position before a bar closes, or in scenarios where algorithmic traders in non-24x7 markets set up after-hours trading capability so that alerts sent after close still have hope of filling before the following day.</p> <p>Note that:</p> <ul> <li>Using strategies with <code dir="auto">process_orders_on_close</code> enabled to send alerts to a third-party service might cause unintended results. Alerts on the close of a bar still occur after the market closes, and real-world orders based on such alerts might not fill until after the market opens again.</li> <li>The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close">strategy.close()</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close_all">strategy.close_all()</a> commands feature an <code dir="auto">immediately</code> parameter that, if <code dir="auto">true</code>, allows the resulting market order to fill on the same tick where the strategy created it. This parameter provides an alternative way for programmers to selectively apply <code dir="auto">process_orders_on_close</code> behavior to closing market orders without affecting the behavior of other order placement commands.</li> </ul> <h2 id="simulating-trading-costs" class="md-heading"><a href="#simulating-trading-costs">Simulating trading costs<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p>Strategy performance reports are more relevant and meaningful when they include potential real-world trading costs. Without modeling the potential costs associated with their trades, traders may overestimate a strategy’s historical profitability, potentially leading to suboptimal decisions in live trading. Pine Script™ strategies include inputs and parameters for simulating trading costs in performance results.</p> <h3 id="commission" class="md-heading"><a href="#commission">Commission<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>Commission is the fee a broker/exchange charges when executing trades. Commission can be a flat fee per trade or contract/share/lot/unit, or a percentage of the total transaction value. Users can set the commission properties of their strategies by including <code dir="auto">commission_type</code> and <code dir="auto">commission_value</code> arguments in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> function, or by setting the “Commission” inputs in the “Properties” tab of the strategy settings.</p> <p>The following script is a simple strategy that simulates a “Long” position of 2% of equity when <code dir="auto">close</code> equals the <code dir="auto">highest</code> value over the <code dir="auto">length</code>, and closes the trade when it equals the <code dir="auto">lowest</code> value:</p> <p><img src="/pine-script-docs/_astro/Strategies-Simulating-trading-costs-Commission-1.XUDZaoNR_2iKnnJ.webp" alt="image" width="1342" height="726" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy(&quot;Commission Demo&quot;, overlay=true, default_qty_value = 2, default_qty_type = strategy.percent_of_equity) length = input.int(10, &quot;Length&quot;) float highest = ta.highest(close, length) float lowest = ta.lowest(close, length) switch close highest =&gt; strategy.entry(&quot;Long&quot;, strategy.long) lowest =&gt; strategy.close(&quot;Long&quot;) plot(highest, color = color.new(color.lime, 50)) plot(lowest, color = color.new(color.red, 50))</div> <p>The results in the <a href="/pine-script-docs/concepts/strategies/#strategy-tester">Strategy Tester</a> show that the strategy had a positive equity growth of 17.61% over the testing range. However, the backtest results do not account for fees the broker/exchange may charge. Let’s see what happens to these results when we include a small commission on every trade in the strategy simulation. In this example, we’ve included <code dir="auto">commission_type = strategy.commission.percent</code> and <code dir="auto">commission_value = 1</code> in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration, meaning it will simulate a commission of 1% on all executed orders:</p> <p><img src="/pine-script-docs/_astro/Strategies-Simulating-trading-costs-Commission-2.DAdgHUnC_4hzO7.webp" alt="image" width="1342" height="726" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy( &quot;Commission Demo&quot;, overlay=true, default_qty_value = 2, default_qty_type = strategy.percent_of_equity, commission_type = strategy.commission.percent, commission_value = 1 ) length = input.int(10, &quot;Length&quot;) float highest = ta.highest(close, length) float lowest = ta.lowest(close, length) switch close highest =&gt; strategy.entry(&quot;Long&quot;, strategy.long) lowest =&gt; strategy.close(&quot;Long&quot;) plot(highest, color = color.new(color.lime, 50)) plot(lowest, color = color.new(color.red, 50))</div> <p>As we can see in the example above, after applying a 1% commission to the backtest, the strategy simulated a significantly reduced net profit of only 1.42% and a more volatile equity curve with an elevated max drawdown. These results highlight the impact that commission can have on a strategy’s hypothetical performance.</p> <h3 id="slippage-and-unfilled-limits" class="md-heading"><a href="#slippage-and-unfilled-limits">Slippage and unfilled limits<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>In real-life trading, a broker/exchange may fill orders at slightly different prices than a trader intended, due to volatility, liquidity, order size, and other market factors, which can profoundly impact a strategy’s performance. The disparity between expected prices and the actual prices at which the broker/exchange executes trades is what we refer to as <em>slippage</em>. Slippage is dynamic and unpredictable, making it impossible to simulate precisely. However, factoring in a small amount of slippage on each trade during a backtest or forward test might help the results better align with reality. Users can model slippage in their strategy results, sized as a fixed number of <em>ticks</em>, by including a <code dir="auto">slippage</code> argument in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement or by setting the “Slippage” input in the “Settings/Properties” tab.</p> <p>The following example demonstrates how simulating slippage affects the fill prices of <a href="/pine-script-docs/concepts/strategies/#market-orders">market orders</a> in a strategy test. The script below places a “Buy” market order of 2% equity when the market price is above a rising EMA and closes the position when the price dips below the EMA while it’s falling. We’ve included <code dir="auto">slippage = 20</code> in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> function, which declares that the price of each simulated order will slip 20 ticks in the direction of the trade.</p> <p>The script uses <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy%7Bdot%7Dopentrades%7Bdot%7Dentry_bar_index">strategy.opentrades.entry_bar_index()</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy%7Bdot%7Dclosedtrades%7Bdot%7Dexit_bar_index">strategy.closedtrades.exit_bar_index()</a> to get the <code dir="auto">entryIndex</code> and <code dir="auto">exitIndex</code>, which it uses to obtain the <code dir="auto">fillPrice</code> of the order. When the bar index is at the <code dir="auto">entryIndex</code>, the <code dir="auto">fillPrice</code> is the first <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy%7Bdot%7Dopentrades%7Bdot%7Dentry_price">strategy.opentrades.entry_price()</a> value. At the <code dir="auto">exitIndex</code>, <code dir="auto">fillPrice</code> is the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy%7Bdot%7Dclosedtrades%7Bdot%7Dexit_price">strategy.closedtrades.exit_price()</a> value from the last closed trade. The script plots the expected fill price along with the simulated fill price after slippage to visually compare the difference:</p> <p><img src="/pine-script-docs/_astro/Strategies-Simulating-trading-costs-Slippage-and-unfilled-limits-1.viLUaTPh_Z17uYCF.webp" alt="image" width="1342" height="680" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy( &quot;Slippage Demo&quot;, overlay = true, slippage = 20, default_qty_value = 2, default_qty_type = strategy.percent_of_equity ) int length = input.int(5, &quot;Length&quot;) //@variable Exponential moving average with an input `length`. float ma = ta.ema(close, length) //@variable Is `true` when `ma` has increased and `close` is above it, `false` otherwise. bool longCondition = close &gt; ma and ma &gt; ma[1] //@variable Is `true` when `ma` has decreased and `close` is below it, `false` otherwise. bool shortCondition = close &lt; ma and ma &lt; ma[1] // Enter a long market position on `longCondition` and close the position on `shortCondition`. if longCondition strategy.entry(&quot;Buy&quot;, strategy.long) if shortCondition strategy.close(&quot;Buy&quot;) //@variable The `bar_index` of the position&#39;s entry order fill. int entryIndex = strategy.opentrades.entry_bar_index(0) //@variable The `bar_index` of the position&#39;s close order fill. int exitIndex = strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1) //@variable The fill price simulated by the strategy. float fillPrice = switch bar_index entryIndex =&gt; strategy.opentrades.entry_price(0) exitIndex =&gt; strategy.closedtrades.exit_price(strategy.closedtrades - 1) //@variable The expected fill price of the open market position. float expectedPrice = not na(fillPrice) ? open : na color expectedColor = na color filledColor = na if bar_index == entryIndex expectedColor := color.green filledColor := color.blue else if bar_index == exitIndex expectedColor := color.red filledColor := color.fuchsia plot(ma, color = color.new(color.orange, 50)) plotchar(not na(fillPrice) ? open : na, &quot;Expected fill price&quot;, &quot;—&quot;, location.absolute, expectedColor) plotchar(fillPrice, &quot;Fill price after slippage&quot;, &quot;—&quot;, location.absolute, filledColor)</div> <p>Note that:</p> <ul> <li>Since the strategy applies constant slippage to all order fills, some orders can fill <em>outside</em> the candle range in the simulation. Exercise caution with this setting, as adding excessive simulated slippage can produce unrealistically worse testing results.</li> </ul> <p>Some traders might assume that they can avoid the adverse effects of slippage by using <a href="/pine-script-docs/concepts/strategies/#limit-orders">limit orders</a>, as unlike <a href="/pine-script-docs/concepts/strategies/#market-orders">market orders</a>, they cannot execute at a worse price than the specified value. However, even if the market price reaches an order’s price, there’s a chance that a limit order might not fill, depending on the state of the real-life market, because limit orders can only fill if a security has sufficient liquidity and price action around their values. To account for the possibility of <em>unfilled</em> orders in a backtest, users can specify the <code dir="auto">backtest_fill_limits_assumption</code> value in the declaration statement or use the “Verify price for limit orders” input in the “Settings/Properties” tab. This setting instructs the strategy to fill limit orders only after the market price moves a defined number of ticks past the order prices.</p> <p>The following example places a limit order of 2% equity at a bar’s <a href="https://www.tradingview.com/pine-script-reference/v6/#var_hlcc4">hlcc4</a> price when the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_high">high</a> is the <code dir="auto">highest</code> value over the past <code dir="auto">length</code> bars and there are no pending entries. The strategy closes the market position and cancels all orders after the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_low">low</a> is the <code dir="auto">lowest</code> value. Each time the strategy triggers an order, it draws a horizontal line at the <code dir="auto">limitPrice</code>, which it updates on each bar until closing the position or canceling the order:</p> <p><img src="/pine-script-docs/_astro/Strategies-Simulating-trading-costs-Slippage-and-unfilled-limits-2.izbF-BkC_2p4GEQ.webp" alt="image" width="1342" height="680" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy( &quot;Verify price for limits example&quot;, overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 2 ) int length = input.int(25, title = &quot;Length&quot;) //@variable Draws a line at the limit price of the most recent entry order. var line limitLine = na // Highest high and lowest low highest = ta.highest(length) lowest = ta.lowest(length) // Place an entry order and draw a new line when the the `high` equals the `highest` value and `limitLine` is `na`. if high == highest and na(limitLine) float limitPrice = hlcc4 strategy.entry(&quot;Long&quot;, strategy.long, limit = limitPrice) limitLine := line.new(bar_index, limitPrice, bar_index + 1, limitPrice) // Close the open market position, cancel orders, and set `limitLine` to `na` when the `low` equals the `lowest` value. if low == lowest strategy.cancel_all() limitLine := na strategy.close_all() // Update the `x2` value of `limitLine` if it isn&#39;t `na`. if not na(limitLine) limitLine.set_x2(bar_index + 1) plot(highest, &quot;Highest High&quot;, color = color.new(color.green, 50)) plot(lowest, &quot;Lowest Low&quot;, color = color.new(color.red, 50))</div> <p>By default, the script assumes that all limit orders are guaranteed to fill when the market price reaches their values, which is often not the case in real-life trading. Let’s add price verification to our limit orders to account for potentially unfilled ones. In this example, we’ve included <code dir="auto">backtest_fill_limits_assumption = 3</code> in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> function call. As we can see, using limit verification omits some simulated order fills and changes the times of others, because the entry orders can now only fill after the price exceeds the limit price by <em>three ticks</em>:</p> <p><img src="/pine-script-docs/_astro/Strategies-Simulating-trading-costs-Slippage-and-unfilled-limits-3.DDaLk5Eu_fLnmo.webp" alt="image" width="1342" height="680" loading="lazy" decoding="async"></p> <aside aria-label="Notice!" class="tv-informer not-content" style="--informer-header-color:#FF9800;--informer-back-color-light:#FFF3E0;--informer-back-color-dark:#33261A"><div class="tv-informer-icon"><svg viewBox="0 0 18 18" width="18" height="18"><path fill-rule="evenodd" d="M9 17A8 8 0 1 0 9 1a8 8 0 0 0 0 16ZM9 4c-.79 0-1.38.7-1.25 1.48l.67 4.03a.59.59 0 0 0 1.16 0l.67-4.03A1.27 1.27 0 0 0 9 4Zm0 8a1 1 0 1 0 0 2 1 1 0 0 0 0-2Z" fill="currentColor"></path></svg></div><div class="tv-informer-content"><p><span class="tv-informer-header">Notice!</span>Limit verification can change the <em>times</em> of some order fills. However, strategies still execute verified limit orders at the same <em>prices</em>. This “time-warping” effect is a compromise that preserves the prices of limit orders, but it can cause a strategy to fill the orders at times that wouldn’t necessarily be possible in the real world. Therefore, users should exercise caution with this setting and understand its limitations when analyzing strategy results.</p></div></aside> <h2 id="risk-management" class="md-heading"><a href="#risk-management">Risk management<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p>Designing a strategy that performs well, especially in a broad class of markets, is a challenging task. Most strategies are designed for specific market patterns/conditions and can produce uncontrolled losses when applied to other data. Therefore, a strategy’s risk management behavior can be critical to its performance. Programmers can set risk management criteria in their strategy scripts using the <code dir="auto">strategy.risk.*()</code> commands.</p> <p>Strategies can incorporate any number of risk management criteria in any combination. All risk management commands execute <em>on every tick and order execution event</em>, regardless of any changes to the strategy’s calculation behavior. There is no way to deactivate any of these commands on specific script executions. Irrespective of a risk management command’s location, it <em>always</em> applies to the strategy unless the programmer removes the call from the code.</p> <p><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy%7Bdot%7Drisk%7Bdot%7Dallow_entry_in">strategy.risk.allow_entry_in()</a></p> <p class="spacer-wrapper"><spacer></spacer>This command overrides the market direction allowed for all <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy%7Bdot%7Dentry">strategy.entry()</a> commands in the script. When a user specifies the trade direction with the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy%7Bdot%7Drisk%7Bdot%7Dallow_entry_in">strategy.risk.allow_entry_in()</a> function (e.g., <a href="https://www.tradingview.com/pine-script-reference/v6/#const_strategy.direction.long">long</a>) the strategy enters trades only in that direction. If a script calls an entry command in the opposite direction while there’s an open market position, the strategy simulates a <a href="/pine-script-docs/concepts/strategies/#market-orders">market order</a> to <em>close</em> the position.</p> <p><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy%7Bdot%7Drisk%7Bdot%7Dmax_cons_loss_days">strategy.risk.max_cons_loss_days()</a></p> <p class="spacer-wrapper"><spacer></spacer>This command cancels all pending orders, closes any open market position, and stops all additional trade actions after the strategy simulates a defined number of trading days with consecutive losses.</p> <p><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy%7Bdot%7Drisk%7Bdot%7Dmax_drawdown">strategy.risk.max_drawdown()</a></p> <p class="spacer-wrapper"><spacer></spacer>This command cancels all pending orders, closes any open market position, and stops all additional trade actions after the strategy’s drawdown reaches the amount specified in the function call.</p> <p><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy%7Bdot%7Drisk%7Bdot%7Dmax_intraday_filled_orders">strategy.risk.max_intraday_filled_orders()</a></p> <p class="spacer-wrapper"><spacer></spacer>This command specifies the maximum number of filled orders per trading day (or per chart bar if the timeframe is higher than daily). If the strategy creates more orders than the maximum, the command cancels all pending orders, closes any open market position, and halts trading activity until the end of the current session.</p> <p><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy%7Bdot%7Drisk%7Bdot%7Dmax_intraday_loss">strategy.risk.max_intraday_loss()</a></p> <p class="spacer-wrapper"><spacer></spacer>This command controls the maximum loss the strategy tolerates per trading day (or per chart bar if the timeframe is higher than daily). When the strategy’s losses reach this threshold, it cancels all pending orders, closes the open market position, and stops all trading activity until the end of the current session.</p> <p><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy%7Bdot%7Drisk%7Bdot%7Dmax_position_size">strategy.risk.max_position_size()</a></p> <p class="spacer-wrapper"><spacer></spacer>This command specifies the maximum possible position size when using <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy%7Bdot%7Dentry">strategy.entry()</a> commands. If the quantity of an entry command results in a market position that exceeds this threshold, the strategy reduces the order quantity so that the resulting position does not exceed the limit.</p> <h2 id="margin" class="md-heading"><a href="#margin">Margin<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p><em>Margin</em> is the minimum percentage of a market position that a trader must hold in their account as collateral to receive and sustain a loan from their broker to achieve their desired <em>leverage</em>. The <code dir="auto">margin_long</code> and <code dir="auto">margin_short</code> parameters of the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement and the “Margin for long/short positions” inputs in the “Properties” tab of the script settings specify margin percentages for long and short positions. For example, if a trader sets the margin for long positions to 25%, they must have enough funds to cover 25% of an open long position. This margin percentage also means the trader can potentially spend up to 400% of their equity on their trades.</p> <p>If a strategy’s simulated funds cannot cover the losses from a margin trade, the broker emulator triggers a <em>margin call</em>, which forcibly liquidates all or part of the open position. The exact number of contracts/shares/lots/units that the emulator liquidates is <em>four times</em> the amount required to cover the loss, which helps prevent constant margin calls on subsequent bars. The emulator determines liquidated quantity using the following algorithm:</p> <ol> <li>Calculate the amount of capital spent on the position: <code dir="auto">Money Spent = Quantity * Entry Price</code></li> <li>Calculate the Market Value of Security (MVS): <code dir="auto">MVS = Position Size * Current Price</code></li> <li>Calculate the Open Profit as the difference between <code dir="auto">MVS</code> and <code dir="auto">Money Spent</code>. If the position is short, multiply this value by -1.</li> <li>Calculate the strategy’s equity value: <code dir="auto">Equity = Initial Capital + Net Profit + Open Profit</code></li> <li>Calculate the margin ratio: <code dir="auto">Margin Ratio = Margin Percent / 100</code></li> <li>Calculate the margin value, which is the cash required to cover the hypothetical account’s portion of the position: <code dir="auto">Margin = MVS * Margin Ratio</code></li> <li>Calculate the strategy’s available funds: <code dir="auto">Available Funds = Equity - Margin</code></li> <li>Calculate the total amount of money lost: <code dir="auto">Loss = Available Funds / Margin Ratio</code></li> <li>Calculate the number of contracts/shares/lots/units the account must liquidate to cover the loss, truncated to the same decimal precision as the minimum position size for the current symbol: <code dir="auto">Cover Amount = TRUNCATE(Loss / Current Price).</code></li> <li>Multiply the quantity required to cover the loss by four to determine the margin call size: <code dir="auto">Margin Call Size = Cover Amount * 4</code></li> </ol> <p>To examine this calculation in detail, let’s add the built-in Supertrend Strategy to the NASDAQ:TSLA chart on the “1D” timeframe and set the “Order size” to 300% of equity and the “Margin for long positions” to 25% in the “Properties” tab of the strategy settings:</p> <p><img src="/pine-script-docs/_astro/Strategies-Margin-1.D7HQz6iZ_Z2vIF4D.webp" alt="image" width="2356" height="1200" loading="lazy" decoding="async"></p> <p>The first entry happened at the bar’s opening price on 16 Sep 2010. The strategy bought 682,438 shares (Position Size) at 4.43 USD (Entry Price). Then, on 23 Sep 2010, when the price dipped to 3.9 (Current Price), the emulator forcibly liquidated 111,052 shares with a margin call. The calculations below show how the broker emulator determined this amount for the margin call event:</p> <div class="expressive-code not-content"><link rel="stylesheet" href="/pine-script-docs/_astro/ec.dtidy.css"/><script type="module" src="/pine-script-docs/_astro/ec.qopfj.js"></script><figure class="frame"><figcaption class="header"></figcaption><pre data-language="text"><code><div class="ec-line"><div class="code"><span style="--0:#e1e4e8;--1:#24292e">Money spent: 682438 * 4.43 = 3023200.34</span></div></div><div class="ec-line"><div class="code"><span style="--0:#e1e4e8;--1:#24292e">MVS: 682438 * 3.9 = 2661508.2</span></div></div><div class="ec-line"><div class="code"><span style="--0:#e1e4e8;--1:#24292e">Open Profit: −361692.14</span></div></div><div class="ec-line"><div class="code"><span style="--0:#e1e4e8;--1:#24292e">Equity: 1000000 + 0 − 361692.14 = 638307.86</span></div></div><div class="ec-line"><div class="code"><span style="--0:#e1e4e8;--1:#24292e">Margin Ratio: 25 / 100 = 0.25</span></div></div><div class="ec-line"><div class="code"><span style="--0:#e1e4e8;--1:#24292e">Margin: 2661508.2 * 0.25 = 665377.05</span></div></div><div class="ec-line"><div class="code"><span style="--0:#e1e4e8;--1:#24292e">Available Funds: 638307.86 - 665377.05 = -27069.19</span></div></div><div class="ec-line"><div class="code"><span style="--0:#e1e4e8;--1:#24292e">Money Lost: -27069.19 / 0.25 = -108276.76</span></div></div><div class="ec-line"><div class="code"><span style="--0:#e1e4e8;--1:#24292e">Cover Amount: TRUNCATE(-108276.76 / 3.9) = TRUNCATE(-27763.27) = -27763</span></div></div><div class="ec-line"><div class="code"><span style="--0:#e1e4e8;--1:#24292e">Margin Call Size: -27763 * 4 = - 111052</span></div></div></code></pre></figure></div> <p>Note that:</p> <ul> <li>The <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.margin_liquidation_price">strategy.margin_liquidation_price</a> variable’s value represents the price level that will cause a margin call if the market price reaches it. For more information about how margin works and the formula for calculating a position’s margin call price, see <a href="https://www.tradingview.com/support/solutions/43000717375-how-do-i-simulate-trading-with-leverage/">this page</a> in our Help Center.</li> </ul> <h2 id="using-strategy-information-in-scripts" class="md-heading"><a href="#using-strategy-information-in-scripts">Using strategy information in scripts<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p>Numerous built-ins within the <code dir="auto">strategy.*</code> namespace and its <em>sub-namespaces</em> provide convenient solutions for programmers to use a strategy’s trade and performance information, including data shown in the <a href="/pine-script-docs/concepts/strategies/#strategy-tester">Strategy Tester</a>, directly within their code’s logic and calculations.</p> <p>Several <code dir="auto">strategy.*</code> variables hold fundamental information about a strategy, including its starting capital, equity, profits and losses, run-up and drawdown, and open position:</p> <ul> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.account_currency">strategy.account_currency</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.initial_capital">strategy.initial_capital</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.equity">strategy.equity</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.netprofit">strategy.netprofit</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.netprofit_percent">strategy.netprofit_percent</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.grossprofit">strategy.grossprofit</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.grossprofit_percent">strategy.grossprofit_percent</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.grossloss">strategy.grossloss</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.grossloss_percent">strategy.grossloss_percent</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.openprofit">strategy.openprofit</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.openprofit_percent">strategy.openprofit_percent</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.max_runup">strategy.max_runup</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.max_runup_percent">strategy.max_runup_percent</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.max_drawdown">strategy.max_drawdown</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.max_drawdown_percent">strategy.max_drawdown_percent</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.position_size">strategy.position_size</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.position_avg_price">strategy.position_avg_price</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.position_entry_name">strategy.position_entry_name</a></li> </ul> <p>Additionally, the namespace features multiple variables that hold general trade information, such as the number of open and closed trades, the number of winning and losing trades, average trade profits, and maximum trade sizes:</p> <ul> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.opentrades">strategy.opentrades</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.closedtrades">strategy.closedtrades</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.wintrades">strategy.wintrades</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.losstrades">strategy.losstrades</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.eventrades">strategy.eventrades</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.avg_trade">strategy.avg_trade</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.avg_trade_percent">strategy.avg_trade_percent</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.avg_winning_trade">strategy.avg_winning_trade</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.avg_winning_trade_percent">strategy.avg_winning_trade_percent</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.avg_losing_trade">strategy.avg_losing_trade</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.avg_losing_trade_percent">strategy.avg_losing_trade_percent</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.max_contracts_held_all">strategy.max_contracts_held_all</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.max_contracts_held_long">strategy.max_contracts_held_long</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.max_contracts_held_short">strategy.max_contracts_held_short</a></li> </ul> <p>Programmers can use these variables to display relevant strategy information on their charts, create customized trading logic based on strategy data, calculate custom performance metrics, and more.</p> <p>The following example demonstrates a few simple use cases for these <code dir="auto">strategy.*</code> variables. The script uses them in its order placement and display calculations. When the calculated <code dir="auto">rank</code> crosses above 10 and the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.opentrades">strategy.opentrades</a> value is 0, the script calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.entry">strategy.entry()</a> to place a “Buy” <a href="/pine-script-docs/concepts/strategies/#market-orders">market order</a>. On the following bar, where that order fills, it calls <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> to create a <a href="/pine-script-docs/concepts/strategies/#take-profit-and-stop-loss">stop-loss</a> order at a user-specified percentage below the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.position_avg_price">strategy.position_avg_price</a>. If the <code dir="auto">rank</code> crosses above 80 during the open trade, the script uses <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close">strategy.close()</a> to exit the position on the next bar.</p> <p>The script draws a <a href="https://www.tradingview.com/pine-script-reference/v6/#type_table">table</a> on the main chart pane displaying formatted strings containing the strategy’s <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.netprofit">net profit</a> and <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.netprofit_percent">net profit percentage</a>, the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.account_currency">account currency</a>, the number of <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.wintrades">winning trades</a> and the win percentage, the ratio of the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.avg_winning_trade">average profit</a> to the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.avg_losing_trade">average loss</a>, and the profit factor (the ratio of the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.grossprofit">gross profit</a> to the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.grossloss">gross loss</a>). It also plots the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.equity">total equity</a> in a separate pane and highlights the pane’s background based on the strategy’s <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.openprofit">open profit</a>:</p> <p><img src="/pine-script-docs/_astro/Strategies-Using-strategy-information-in-scripts-1.BielLwmZ_iHnPr.webp" alt="image" width="1336" height="570" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy( &quot;Using strategy information demo&quot;, default_qty_type = strategy.percent_of_equity, default_qty_value = 5, margin_long = 100, margin_short = 100 ) //@variable The number of bars in the `rank` calculation. int lengthInput = input.int(50, &quot;Length&quot;, 1) //@variable The stop-loss percentage. float slPercentInput = input.float(4.0, &quot;SL %&quot;, 0.0, 100.0) / 100.0 //@variable The percent rank of `close` prices over `lengthInput` bars. float rank = ta.percentrank(close, lengthInput) // Entry and exit signals. bool entrySignal = ta.crossover(rank, 10) and strategy.opentrades == 0 bool exitSignal = ta.crossover(rank, 80) and strategy.opentrades == 1 // Place orders based on the `entrySignal` and `exitSignal` occurrences. switch entrySignal =&gt; strategy.entry(&quot;Buy&quot;, strategy.long) entrySignal[1] =&gt; strategy.exit(&quot;SL&quot;, &quot;Buy&quot;, stop = strategy.position_avg_price * (1.0 - slPercentInput)) exitSignal =&gt; strategy.close(&quot;Buy&quot;) if barstate.islastconfirmedhistory or barstate.isrealtime //@variable A table displaying strategy information on the main chart pane. var table dashboard = table.new( position.top_right, 2, 10, border_color = chart.fg_color, border_width = 1, force_overlay = true ) //@variable The strategy&#39;s currency. string currency = strategy.account_currency // Display the net profit as a currency amount and percentage. dashboard.cell(0, 1, &quot;Net P/L&quot;) dashboard.cell( 1, 1, str.format(&quot;{0, number, 0.00} {1} ({2}%)&quot;, strategy.netprofit, currency, strategy.netprofit_percent), text_color = chart.fg_color, bgcolor = strategy.netprofit &gt; 0 ? color.lime : color.red ) // Display the number of winning trades as an absolute value and percentage of all completed trades. dashboard.cell(0, 2, &quot;Winning trades&quot;) dashboard.cell( 1, 2, str.format(&quot;{0} ({1, number, #.##%})&quot;, strategy.wintrades, strategy.wintrades / strategy.closedtrades), text_color = chart.fg_color, bgcolor = strategy.wintrades &gt; strategy.losstrades ? color.lime : color.red ) // Display the ratio of average trade profit to average trade loss. dashboard.cell(0, 3, &quot;Avg. win / Avg. loss&quot;) dashboard.cell( 1, 3, str.format(&quot;{0, number, #.###}&quot;, strategy.avg_winning_trade / strategy.avg_losing_trade), text_color = chart.fg_color, bgcolor = strategy.avg_winning_trade &gt; strategy.avg_losing_trade ? color.lime : color.red ) // Display the profit factor, i.e., the ratio of gross profit to gross loss. dashboard.cell(0, 4, &quot;Profit factor&quot;) dashboard.cell( 1, 4, str.format(&quot;{0, number, #.###}&quot;, strategy.grossprofit / strategy.grossloss), text_color = chart.fg_color, bgcolor = strategy.grossprofit &gt; strategy.grossloss ? color.lime : color.red ) // Plot the current equity in a separate pane and highlight the pane&#39;s background while there is an open position. plot(strategy.equity, &quot;Total equity&quot;, strategy.equity &gt; strategy.initial_capital ? color.teal : color.maroon, 3) bgcolor( strategy.openprofit &gt; 0 ? color.new(color.teal, 80) : strategy.openprofit &lt; 0 ? color.new(color.maroon, 80) : na, title = &quot;Open position highlight&quot; )</div> <p>Note that:</p> <ul> <li>This script creates a <a href="/pine-script-docs/concepts/strategies/#take-profit-and-stop-loss">stop-loss</a> order one bar after the entry order because it uses <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.position_avg_price">strategy.position_avg_price</a> to determine the price level. This variable has a non-na value only when the strategy has an <em>open position</em>.</li> <li>The script only draws the <a href="https://www.tradingview.com/pine-script-reference/v6/#type_table">table</a> on the last historical bar and all realtime bars because the historical states of <a href="/pine-script-docs/concepts/tables/">tables</a> are <strong>never visible</strong>. See the <a href="/pine-script-docs/writing/profiling-and-optimization/#reducing-drawing-updates">Reducing drawing updates</a> section of the <a href="/pine-script-docs/writing/profiling-and-optimization/">Profiling and optimization</a> page for more information.</li> <li>We included <code dir="auto">force_overlay = true</code> in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_table.new">table.new()</a> call to display the table on the main chart pane.</li> </ul> <h3 id="individual-trade-information" class="md-heading"><a href="#individual-trade-information">Individual trade information<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>The <code dir="auto">strategy.*</code> namespace features two sub-namespaces that provide access to <em>individual trade</em> information: <code dir="auto">strategy.opentrades.*</code> and <code dir="auto">strategy.closedtrades.*</code>. The <code dir="auto">strategy.opentrades.*</code> built-ins return data for <em>incomplete</em> (open) trades, and the <code dir="auto">strategy.closedtrades.*</code> built-ins return data for <em>completed</em> (closed) trades. With these built-ins, programmers can use granular trade data in their scripts, allowing for more detailed strategy analysis and advanced calculations.</p> <p>Both sub-namespaces contain several similar functions that return information about a trade’s orders, simulated costs, and profit/loss, including:</p> <ul> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.opentrades.entry_id">strategy.opentrades.entry_id()</a> / <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.entry_id">strategy.closedtrades.entry_id()</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.opentrades.entry_price">strategy.opentrades.entry_price()</a> / <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.entry_price">strategy.closedtrades.entry_price()</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.opentrades.entry_bar_index">strategy.opentrades.entry_bar_index()</a> / <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.entry_bar_index">strategy.closedtrades.entry_bar_index()</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.opentrades.entry_time">strategy.opentrades.entry_time()</a> / <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.entry_time">strategy.closedtrades.entry_time()</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.opentrades.entry_comment">strategy.opentrades.entry_comment()</a> / <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.entry_comment">strategy.closedtrades.entry_comment()</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.opentrades.size">strategy.opentrades.size()</a> / <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.size">strategy.closedtrades.size()</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.opentrades.profit">strategy.opentrades.profit()</a> / <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.profit">strategy.closedtrades.profit()</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.opentrades.profit_percent">strategy.opentrades.profit_percent()</a> / <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.profit_percent">strategy.closedtrades.profit_percent()</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.opentrades.commission">strategy.opentrades.commission()</a> / <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.commission">strategy.closedtrades.commission()</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.opentrades.max_runup">strategy.opentrades.max_runup()</a> / <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.max_runup">strategy.closedtrades.max_runup()</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.opentrades.max_runup_percent">strategy.opentrades.max_runup_percent()</a> / <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.max_runup_percent">strategy.closedtrades.max_runup_percent()</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.opentrades.max_drawdown">strategy.opentrades.max_drawdown()</a> / <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.max_drawdown">strategy.closedtrades.max_drawdown()</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.opentrades.max_drawdown_percent">strategy.opentrades.max_drawdown_percent()</a> / <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.max_drawdown_percent">strategy.closedtrades.max_drawdown_percent()</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.exit_id">strategy.closedtrades.exit_id()</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.exit_price">strategy.closedtrades.exit_price()</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.exit_time">strategy.closedtrades.exit_time()</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.exit_bar_index">strategy.closedtrades.exit_bar_index()</a></li> <li><a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.exit_comment">strategy.closedtrades.exit_comment()</a></li> </ul> <p>Note that:</p> <ul> <li>Most built-ins within these namespaces are <em>functions</em>. However, the <code dir="auto">strategy.opentrades.*</code> namespace also features a unique <em>variable</em>: <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.opentrades.capital_held">strategy.opentrades.capital_held</a>. Its value represents the amount of capital reserved by <em>all</em> open trades.</li> <li>Only the <code dir="auto">strategy.closedtrades.*</code> namespace has <code dir="auto">.exit_*()</code> functions that return information about <em>exit orders</em>.</li> </ul> <p>All <code dir="auto">strategy.opentrades.*()</code> and <code dir="auto">strategy.closedtrades.*()</code> functions have a <code dir="auto">trade_num</code> parameter, which accepts an “int” value representing the index of the open or closed trade. The index of the first open/closed trade is 0, and the last trade’s index is <em>one less</em> than the value of the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.opentrades">strategy.opentrades</a>/<a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.closedtrades">strategy.closedtrades</a> variable.</p> <p>The following example places up to five long entry orders per position, each with a unique ID, and it calculates metrics for specific closed trades.</p> <p>The strategy places a new entry order when the <a href="https://www.tradingview.com/pine-script-reference/v6/#var_close">close</a> crosses above its <code dir="auto">median</code> without reaching the <code dir="auto">highest</code> value, but only if the number of <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.opentrades">open trades</a> is less than five. It exits each position using <a href="/pine-script-docs/concepts/strategies/#take-profit-and-stop-loss">stop-loss</a> orders from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> or a <a href="/pine-script-docs/concepts/strategies/#market-orders">market order</a> from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.close_all">strategy.close_all()</a>. Each successive entry order’s ID depends on the number of open trades. The first entry ID in each position is “Buy0”, and the last possible entry ID is “Buy4”.</p> <p>The script calls <code dir="auto">strategy.closedtrades.*()</code> functions within a <a href="https://www.tradingview.com/pine-script-reference/v6/#kw_for">for</a> loop to access closed trade <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.entry_id">entry IDs</a>, <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.profit">profits</a>, <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.entry_bar_index">entry bar indices</a>, and <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.closedtrades.exit_bar_index">exit bar indices</a>. It uses this information to calculate the total number of closed trades with the specified entry ID, the number of winning trades, the average number of bars per trade, and the total profit from all the trades. The script then organizes this information in a formatted string and displays it in a single-cell <a href="https://www.tradingview.com/pine-script-reference/v6/#type_table">table</a>:</p> <p><img src="/pine-script-docs/_astro/Strategies-Using-strategy-information-in-scripts-Individual-trade-information-1.Clxqg8tA_Z1Uq1KB.webp" alt="image" width="1336" height="500" loading="lazy" decoding="async"></p> <div class="pine-colorizer not-content">//@version=6 strategy( &quot;Individual trade information demo&quot;, pyramiding = 5, default_qty_type = strategy.percent_of_equity, default_qty_value = 1, margin_long = 100, margin_short = 100 ) //@variable The number of bars in the `highest` and `lowest` calculation. int lengthInput = input.int(50, &quot;Length&quot;, 1) string idInput = input.string(&quot;Buy0&quot;, &quot;Entry ID to analyze&quot;, [&quot;Buy0&quot;, &quot;Buy1&quot;, &quot;Buy2&quot;, &quot;Buy3&quot;, &quot;Buy4&quot;]) // Calculate the highest, lowest, and median `close` values over `lengthInput` bars. float highest = ta.highest(close, lengthInput) float lowest = ta.lowest(close, lengthInput) float median = 0.5 * (highest + lowest) // Define entry and stop-loss orders when the `close` crosses above the `median` without touching the `highest` value. if ta.crossover(close, median) and close != highest and strategy.opentrades &lt; 5 strategy.entry(&quot;Buy&quot; + str.tostring(strategy.opentrades), strategy.long) if strategy.opentrades == 0 strategy.exit(&quot;SL&quot;, stop = lowest) // Close the entire position when the `close` reaches the `lowest` value. if close == lowest strategy.close_all() // The total number of closed trades with the `idInput` entry, the number of wins, the average number of bars, // and the total profit. int trades = 0 int wins = 0 float avgBars = 0 float totalPL = 0.0 if barstate.islastconfirmedhistory or barstate.isrealtime //@variable A single-cell table displaying information about closed trades with the `idInput` entry ID. var table infoTable = table.new(position.middle_center, 1, 1, color.purple) // Iterate over closed trade indices. for tradeNum = 0 to strategy.closedtrades - 1 // Skip the rest of the current iteration if the `tradeNum` closed trade didn&#39;t open with an `idInput` entry. if strategy.closedtrades.entry_id(tradeNum) != idInput continue // Accumulate `trades`, `wins`, `avgBars`, and `totalPL` values. float profit = strategy.closedtrades.profit(tradeNum) trades += 1 wins += profit &gt; 0 ? 1 : 0 avgBars += strategy.closedtrades.exit_bar_index(tradeNum) - strategy.closedtrades.entry_bar_index(tradeNum) + 1 totalPL += profit avgBars /= trades //@variable A formatted string containing the calculated closed trade information. string displayText = str.format( &quot;ID: {0}\n\nTotal trades: {1}\nWin trades: {2}\nAvg. bars: {3}\nTotal P/L: {4} {5}&quot;, idInput, trades, wins, avgBars, totalPL, strategy.account_currency ) // Populate the table&#39;s cell with `displayText`. infoTable.cell(0, 0, displayText, text_color = color.white, text_halign = text.align_left, text_size = size.large) // Plot the highest, median, and lowest values on the main chart pane. plot(highest, &quot;Highest close&quot;, force_overlay = true) plot(median, &quot;Median close&quot;, force_overlay = true) plot(lowest, &quot;Lowest close&quot;, force_overlay = true)</div> <p>Note that:</p> <ul> <li>This strategy can open up to five long trades per position because we included <code dir="auto">pyramiding = 5</code> in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement. See the <a href="/pine-script-docs/concepts/strategies/#pyramiding">pyramiding</a> section for more information.</li> <li>The <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy.exit">strategy.exit()</a> instance in this script persists and generates exit orders for every entry in the open position because we did not specify a <code dir="auto">from_entry</code> ID. See the <a href="/pine-script-docs/concepts/strategies/#exits-for-multiple-entries">Exits for multiple entries</a> section to learn more about this behavior.</li> </ul> <h2 id="strategy-alerts" class="md-heading"><a href="#strategy-alerts">Strategy alerts<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p>Pine Script™ indicators (not strategies) have two different mechanisms to set up custom alert conditions: the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_alertcondition">alertcondition()</a> function, which tracks one specific condition per function call, and the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_alert">alert()</a> function, which tracks all its calls simultaneously, but provides greater flexibility in the number of calls, alert messages, etc.</p> <p>Pine Script™ strategies cannot create alert triggers using the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_alertcondition">alertcondition()</a> function, but they can create triggers with the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_alert">alert()</a> function. Additionally, each <a href="/pine-script-docs/concepts/strategies/#order-placement-and-cancellation">order placement command</a> comes with its own built-in alert functionality that does not require any additional code to implement. As such, any strategy that uses an order placement command can issue alerts upon order execution. The precise mechanics of such built-in strategy alerts are described in the <a href="/pine-script-docs/concepts/alerts/#order-fill-events">Order Fill events</a> section of the <a href="/pine-script-docs/concepts/alerts/">Alerts</a> page.</p> <p>When a strategy uses both the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_alert">alert()</a> function and functions that create orders in the same script, the “Create Alert” dialog box provides a choice between the conditions to use as a trigger: <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_alert">alert()</a> events, order fill events, or both.</p> <p>For many trading strategies, the delay between a triggered alert and a live trade can be a critical performance factor. By default, strategy scripts can only execute <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_alert">alert()</a> function calls on the close of realtime bars, as if they used <a href="https://www.tradingview.com/pine-script-reference/v6/#const_alert%7Bdot%7Dfreq_once_per_bar_close">alert.freq_once_per_bar_close</a>, regardless of the <code dir="auto">freq</code> argument in the call. Users can change the alert frequency by including <code dir="auto">calc_on_every_tick = true</code> in the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> call or selecting the “Recalculate/On every tick” option in the “Settings/Properties” tab before creating the alert. However, depending on the script, this setting can adversely impact the strategy’s behavior. See the <a href="/pine-script-docs/concepts/strategies/#calc_on_every_tick">`calc_on_every_tick`</a> section for more information.</p> <p>Order fill alert triggers do not suffer the same limitations as the triggers from <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_alert">alert()</a> calls, which makes them more suitable for sending alerts to third parties for automation. Alerts from order fill events execute <em>immediately</em>, unaffected by a script’s <code dir="auto">calc_on_every_tick</code> setting. Users can set the default message for order fill alerts via the <code dir="auto">//@strategy_alert_message</code> compiler annotation. The text provided with this annotation populates the “Message” field in the “Create Alert” dialog box.</p> <p>The following script shows a simple example of a default order fill alert message. Above the <a href="https://www.tradingview.com/pine-script-reference/v6/#fun_strategy">strategy()</a> declaration statement, the script includes <code dir="auto">@strategy_alert_message</code> with <a href="https://www.tradingview.com/support/solutions/43000531021-how-to-use-a-variable-value-in-alert/"><em>placeholders</em></a> for the trade action, current position size, ticker name, and fill price values in the message text:</p> <div class="pine-colorizer not-content">//@version=6 //@strategy_alert_message {{strategy.order.action}} {{strategy.position_size}} {{ticker}} @ {{strategy.order.price}} strategy(&quot;Alert Message Demo&quot;, overlay = true) float fastMa = ta.sma(close, 5) float slowMa = ta.sma(close, 10) if ta.crossover(fastMa, slowMa) strategy.entry(&quot;buy&quot;, strategy.long) if ta.crossunder(fastMa, slowMa) strategy.entry(&quot;sell&quot;, strategy.short) plot(fastMa, &quot;Fast MA&quot;, color.aqua) plot(slowMa, &quot;Slow MA&quot;, color.orange)</div> <p>This script populates the “Create Alert” dialog box with its default message when the user selects its name from the “Condition” dropdown tab:</p> <p><img src="/pine-script-docs/_astro/Strategies-Strategy-alerts-1.BxOEoyCe_ZM3QoM.webp" alt="image" width="902" height="578" loading="lazy" decoding="async"></p> <p>When the alert fires, the strategy populates the placeholders in the alert message with their corresponding values. For example:</p> <p><img src="/pine-script-docs/_astro/Strategies-Strategy-alerts-2.RsPPvOvM_1vSwtv.webp" alt="image" width="634" height="360" loading="lazy" decoding="async"></p> <h2 id="notes-on-testing-strategies" class="md-heading"><a href="#notes-on-testing-strategies">Notes on testing strategies<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h2> <p>Testing and tuning strategies in historical and live market conditions can provide insight into a strategy’s characteristics, potential weaknesses, and <em>possibly</em> its future potential. However, traders should always be aware of the biases and limitations of simulated strategy results, especially when using the results to support live trading decisions. This section outlines some caveats associated with strategy validation and tuning and possible solutions to mitigate their effects.</p> <aside aria-label="Notice!" class="tv-informer not-content" style="--informer-header-color:#FF9800;--informer-back-color-light:#FFF3E0;--informer-back-color-dark:#33261A"><div class="tv-informer-icon"><svg viewBox="0 0 18 18" width="18" height="18"><path fill-rule="evenodd" d="M9 17A8 8 0 1 0 9 1a8 8 0 0 0 0 16ZM9 4c-.79 0-1.38.7-1.25 1.48l.67 4.03a.59.59 0 0 0 1.16 0l.67-4.03A1.27 1.27 0 0 0 9 4Zm0 8a1 1 0 1 0 0 2 1 1 0 0 0 0-2Z" fill="currentColor"></path></svg></div><div class="tv-informer-content"><p><span class="tv-informer-header">Notice!</span>Although testing strategies on existing data might give traders helpful information about a strategy’s qualities, it’s important to note that neither the past nor the present guarantees the future. Financial markets can change rapidly and unpredictably, which can cause a strategy to sustain uncontrollable losses. Additionally, simulated results may not fully account for other real-world factors that can impact trading performance. Therefore, we recommend that traders thoroughly understand the limitations and risks of backtests and forward tests and consider them “parts of the whole” in their validation processes rather than basing decisions solely on the results.</p></div></aside> <h3 id="backtesting-and-forward-testing" class="md-heading"><a href="#backtesting-and-forward-testing">Backtesting and forward testing<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p><em>Backtesting</em> is a technique to evaluate the historical performance of a trading strategy or model by simulating and analyzing its past results on historical market data. This technique assumes that a strategy’s results on past data can provide insight into its strengths and weaknesses. When backtesting, many traders adjust the parameters of a strategy in an attempt to optimize its results. Analysis and optimization of historical results can help traders to gain a deeper understanding of a strategy. However, traders should always understand the risks and limitations when basing their decisions on optimized backtest results.</p> <p>It is prudent to also use realtime analysis as a tool for evaluating a trading system on a forward-looking basis. <em>Forward testing</em> aims to gauge the performance of a strategy in live market conditions, where factors such as trading costs, slippage, and liquidity can meaningfully affect its performance. While forward testing has the distinct advantage of not being affected by certain types of biases (e.g., lookahead bias or “future data leakage”), it does carry the disadvantage of being limited in the quantity of data to test. Therefore, although it can provide helpful insights into a strategy’s performance in current market conditions, forward testing is not typically used on its own.</p> <h3 id="lookahead-bias" class="md-heading"><a href="#lookahead-bias">Lookahead bias<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>One typical issue in backtesting strategies that request alternate timeframe data, use repainting variables such as <a href="https://www.tradingview.com/pine-script-reference/v6/#var_timenow">timenow</a>, or alter calculation behavior for intrabar order fills, is the leakage of future data into the past during evaluation, which is known as <em>lookahead bias</em>. Not only is this bias a common cause of unrealistic strategy results, since the future is never actually knowable beforehand, but it is also one of the typical causes of strategy repainting.</p> <p>Traders can often confirm whether a strategy has lookahead bias by forward testing it on realtime data, where no known data exists beyond the latest bar. Since there is no future data to leak into the past on realtime bars, the strategy will behave differently on historical and realtime bars if its results have lookahead bias.</p> <p>To eliminate lookahead bias in a strategy:</p> <ul> <li>Do not use repainting variables that leak future values into the past in the order placement or cancellation logic.</li> <li>Do not include <a href="https://www.tradingview.com/pine-script-reference/v6/#const_barmerge%7Bdot%7Dlookahead_on">barmerge.lookahead_on</a> in <code dir="auto">request.*()</code> calls without offsetting the data series, as described in <a href="/pine-script-docs/concepts/repainting/#future-leak-with-requestsecurity">this</a> section of the <a href="/pine-script-docs/concepts/repainting/">Repainting</a> page.</li> <li>Use realistic strategy calculation behavior.</li> </ul> <h3 id="selection-bias" class="md-heading"><a href="#selection-bias">Selection bias<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>Selection bias occurs when a trader analyzes only results on specific instruments or timeframes while ignoring others. This bias can distort the perspective of the strategy’s robustness, which can impact trading decisions and performance optimizations. Traders can reduce the effects of selection bias by evaluating their strategies on multiple, ideally diverse, symbols and timeframes, and ensuring not to ignore poor performance results or “cherry-pick” testing ranges.</p> <h3 id="overfitting" class="md-heading"><a href="#overfitting">Overfitting<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>A common problem when optimizing a strategy based on backtest results is overfitting (“curve fitting”), which means tailoring the strategy for specific data. An overfitted strategy often fails to generalize well on new, unseen data. One widely-used approach to help reduce the potential for overfitting and promote better generalization is to split an instrument’s data into two or more parts to test the strategy outside the sample used for optimization, otherwise known as “in-sample” (IS) and “out-of-sample” (OOS) backtesting.</p> <p>In this approach, traders optimize strategy parameters on the IS data, and they test the optimized configuration on the OOS data without additional fine-tuning. Although this and other, more robust approaches might provide a glimpse into how a strategy might fare after optimization, traders should still exercise caution. No trading strategy can guarantee future performance, regardless of the data used for optimization and testing, because the future is inherently unknowable.</p> <h3 id="order-limit" class="md-heading"><a href="#order-limit">Order limit<span class="icon icon-link" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 28 28"><g fill="currentColor" clip-path="url(#a)"><path d="M14.908 5.558a5.326 5.326 0 1 1 7.533 7.533l-3.236 3.236-1.061-1.061 3.236-3.236a3.826 3.826 0 1 0-5.411-5.411l-3.236 3.236-1.06-1.06 3.235-3.237ZM5.56 14.907a5.326 5.326 0 0 0 7.532 7.533l3.236-3.236-1.061-1.061-3.236 3.236a3.826 3.826 0 1 1-5.411-5.411l3.236-3.236-1.061-1.06-3.236 3.235Z"></path><path d="m16.346 10.592-5.753 5.753 1.061 1.06 5.753-5.752-1.06-1.06Z"></path></g><defs><clippath id="a"><path fill="#fff" d="M0 0h28v28H0z"></path></clippath></defs></svg></span></a></h3> <p>Outside of Deep Backtesting, a strategy can keep track of up to 9000 orders. If a strategy creates more than 9000 orders, the earliest orders are <em>trimmed</em> so that the strategy stores the information for only the most recent orders.</p> <p>Trimmed orders do <strong>not</strong> appear in the <a href="/pine-script-docs/concepts/strategies/#strategy-tester">Strategy Tester</a>. Referencing the trimmed order IDs using <code dir="auto">strategy.closedtrades.*</code> functions returns <a href="https://www.tradingview.com/pine-script-reference/v6/#var_na">na</a>.</p> <p>The <a href="https://www.tradingview.com/pine-script-reference/v6/#var_strategy.closedtrades.first_index">strategy.closedtrades.first_index</a> variable holds the index of the oldest <em>untrimmed</em> trade, which corresponds to the first trade listed in the <a href="/pine-script-docs/concepts/strategies/#list-of-trades">List of Trades</a>. If the strategy creates less than 9000 orders, there are no trimmed orders, and this variable’s value is 0.</p> </div> <div class="pagination-buttons not-content" data-astro-cid-xgirumru> <a href="/pine-script-docs/concepts/sessions" class="pagination-card" data-pagefind-ignore data-astro-cid-assl6cvf> <p data-astro-cid-assl6cvf>Previous</p> <h4 class="pagination-card-header" data-astro-cid-assl6cvf> <svg width="28" height="28" viewBox="0 0 28 28" data-astro-cid-assl6cvf data-icon="theme/arrow-back"> <use xlink:href="#ai:local:theme/arrow-back"></use> </svg> Sessions </h4> </a> <a href="/pine-script-docs/concepts/tables" class="pagination-card" data-pagefind-ignore data-astro-cid-assl6cvf> <p data-astro-cid-assl6cvf>Next</p> <h4 class="pagination-card-header" data-astro-cid-assl6cvf> Tables <svg width="28" height="28" viewBox="0 0 28 28" data-astro-cid-assl6cvf data-icon="theme/arrow"> <symbol id="ai:local:theme/arrow"><path fill="none" stroke="var(--arrow-fill-color, #131722)" d="m11 8 6 6-6 6"/></symbol><use xlink:href="#ai:local:theme/arrow"></use> </svg> </h4> </a> </div> </main> <div id="toc" data-pagefind-ignore="all" data-astro-cid-oor6cujd><aside class="document-toc-container ml-4 w-48" data-astro-cid-oor6cujd><section id="toc-scroll-section" class="slick-scroll" data-astro-cid-oor6cujd><header data-astro-cid-oor6cujd><h2 class="toc-header" data-astro-cid-oor6cujd>On this page</h2></header><ul class="" id="toc-entries" data-astro-cid-oor6cujd><a href="#introduction" aria-current="true" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-current data-astro-cid-oor6cujd>Introduction</li></a><a href="#a-simple-strategy-example" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-astro-cid-oor6cujd>A simple strategy example</li></a><a href="#applying-a-strategy-to-a-chart" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-astro-cid-oor6cujd>Applying a strategy to a chart</li></a><a href="#strategy-tester" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-astro-cid-oor6cujd>Strategy Tester</li></a><a href="#overview" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>Overview</li></a><a href="#performance-summary" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>Performance Summary</li></a><a href="#list-of-trades" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>List of Trades</li></a><a href="#properties" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>Properties</li></a><a href="#broker-emulator" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-astro-cid-oor6cujd>Broker emulator</li></a><a href="#bar-magnifier" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>Bar magnifier</li></a><a href="#orders-and-trades" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-astro-cid-oor6cujd>Orders and trades</li></a><a href="#order-types" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-astro-cid-oor6cujd>Order types</li></a><a href="#market-orders" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>Market orders</li></a><a href="#limit-orders" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>Limit orders</li></a><a href="#stop-and-stop-limit-orders" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>Stop and stop-limit orders</li></a><a href="#order-placement-and-cancellation" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-astro-cid-oor6cujd>Order placement and cancellation</li></a><a href="#strategyentry" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>&#96strategy.entry()&#96</li></a><a href="#reversing-positions" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-4" data-astro-cid-oor6cujd>Reversing positions</li></a><a href="#pyramiding" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-4" data-astro-cid-oor6cujd>Pyramiding</li></a><a href="#strategyorder" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>&#96strategy.order()&#96</li></a><a href="#strategyexit" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>&#96strategy.exit()&#96</li></a><a href="#take-profit-and-stop-loss" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-4" data-astro-cid-oor6cujd>Take-profit and stop-loss</li></a><a href="#partial-and-multi-level-exits" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-4" data-astro-cid-oor6cujd>Partial and multi-level exits</li></a><a href="#trailing-stops" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-4" data-astro-cid-oor6cujd>Trailing stops</li></a><a href="#exits-for-multiple-entries" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-4" data-astro-cid-oor6cujd>Exits for multiple entries</li></a><a href="#strategyclose-and-strategyclose_all" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>&#96strategy.close()&#96 and &#96strategy.close_all()&#96</li></a><a href="#strategycancel-and-strategycancel_all" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>&#96strategy.cancel()&#96 and &#96strategy.cancel_all()&#96</li></a><a href="#position-sizing" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-astro-cid-oor6cujd>Position sizing</li></a><a href="#closing-a-market-position" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-astro-cid-oor6cujd>Closing a market position</li></a><a href="#oca-groups" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-astro-cid-oor6cujd>OCA groups</li></a><a href="#strategyocacancel" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>&#96strategy.oca.cancel&#96</li></a><a href="#strategyocareduce" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>&#96strategy.oca.reduce&#96</li></a><a href="#strategyocanone" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>&#96strategy.oca.none&#96</li></a><a href="#currency" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-astro-cid-oor6cujd>Currency</li></a><a href="#altering-calculation-behavior" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-astro-cid-oor6cujd>Altering calculation behavior</li></a><a href="#calc_on_every_tick" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>&#96calc_on_every_tick&#96</li></a><a href="#calc_on_order_fills" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>&#96calc_on_order_fills&#96</li></a><a href="#process_orders_on_close" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>&#96process_orders_on_close&#96</li></a><a href="#simulating-trading-costs" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-astro-cid-oor6cujd>Simulating trading costs</li></a><a href="#commission" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>Commission</li></a><a href="#slippage-and-unfilled-limits" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>Slippage and unfilled limits</li></a><a href="#risk-management" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-astro-cid-oor6cujd>Risk management</li></a><a href="#margin" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-astro-cid-oor6cujd>Margin</li></a><a href="#using-strategy-information-in-scripts" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-astro-cid-oor6cujd>Using strategy information in scripts</li></a><a href="#individual-trade-information" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>Individual trade information</li></a><a href="#strategy-alerts" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-astro-cid-oor6cujd>Strategy alerts</li></a><a href="#notes-on-testing-strategies" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-2" data-astro-cid-oor6cujd>Notes on testing strategies</li></a><a href="#backtesting-and-forward-testing" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>Backtesting and forward testing</li></a><a href="#lookahead-bias" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>Lookahead bias</li></a><a href="#selection-bias" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>Selection bias</li></a><a href="#overfitting" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>Overfitting</li></a><a href="#order-limit" class="document-toc-link" data-astro-cid-oor6cujd><li class="l-3" data-astro-cid-oor6cujd>Order limit</li></a></ul></section><div class="toc-bottom-fade" data-astro-cid-oor6cujd></div><div class="back-top-space" data-astro-cid-oor6cujd><div class="not-content" style="" data-astro-cid-pkzv2hgs> <a id="back-top-button" title="Back to top" href="#top" data-astro-cid-pkzv2hgs class="floating-button not-content stvb-base stvb-pointer stvb-gray stvb-medium stvb-secondary stvb-icon stvb-icon-force-color stvb-force-no-border"> <svg width="18" height="18" viewBox="0 0 18 18" data-astro-cid-oor6cujd data-icon="theme/arrow-up"> <symbol id="ai:local:theme/arrow-up"><g fill="none"><g clip-path="url(#a)"><path fill="currentColor" fill-rule="evenodd" d="m9 3.5.5.44 4 3.5-1 1.12-2.75-2.4V14h-1.5V6.15L5.49 8.56l-.98-1.12 4-3.5L9 3.5Z" clip-rule="evenodd"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h18v18H0z"/></clipPath></defs></g></symbol><use xlink:href="#ai:local:theme/arrow-up"></use> </svg> </a> </div> </div></aside></div> </main> </div> <footer data-astro-cid-b6pf7ola> <div class="footer-content" data-astro-cid-b6pf7ola> <ul data-astro-cid-b6pf7ola> <li data-astro-cid-b6pf7ola> <a href="https://www.tradingview.com/chat/#BfmVowG1TZkKO235" data-astro-cid-b6pf7ola>Pine Q&amp;A chat</a> </li><li data-astro-cid-b6pf7ola> <a href="https://stackoverflow.com/questions/tagged/pine-script" data-astro-cid-b6pf7ola>Stack Overflow</a> ↗ </li><li data-astro-cid-b6pf7ola> <a href="https://t.me/PineCodersQA" data-astro-cid-b6pf7ola>Telegram</a> ↗ </li><li data-astro-cid-b6pf7ola> <a href="https://www.reddit.com/r/TradingView/" data-astro-cid-b6pf7ola>Reddit</a> ↗ </li> </ul> <div class="flex" data-astro-cid-b6pf7ola></div> <div class="copyright" data-astro-cid-b6pf7ola>Copyright © 2024 TradingView, Inc.</div> </div> </footer> </body></html>

Pages: 1 2 3 4 5 6 7 8 9 10