// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // (c) trade-commander.com //@version=6 // New Order Copier - order types demo. Walks through every order type the copier // takes from TradingView, one step every `Bars per step` real-time bars: // 0 LIMIT buy with SL/TP placed 1 modified 2 cancelled // 3 STOP sell with SL/TP placed 4 modified 5 cancelled // 6 STOP LIMIT buy with SL/TP placed 7 modified 8 cancelled // 9 MARKET buy with SL/TP 10 SL/TP moved 11 closed // Resting orders are placed 3 ATR away from the price so that they do not fill. // Alert: condition = this script, "alert() function calls only", webhook URL from // New Order Copier. Enter the source token in the script settings BEFORE creating it. strategy("NOC order types demo", overlay = true, calc_on_every_tick = false) // ===== NOC functions BEGIN - copy this whole block into your own strategy ===== // Turns the strategy's orders into New Order Copier messages: market, limit, stop and // stop limit, each with optional stop loss / take profit; changes and cancels follow. // Every function returns the alert text, or "" when there is nothing to send - pass a // non-empty text to alert(). Only real-time bars send. // @type One order as last sent to the copier. Keyed by its oid in the NocBook. // @field side "BUY" or "SELL". // @field otype "MKT", "LMT", "STP" or "STPLMT". // @field qty Quantity in the NocBook's qty unit. // @field price Limit price (LMT, STPLMT), else na. // @field stopPrice Trigger price (STP, STPLMT), else na. // @field sl Attached stop loss, na = none. // @field tp Attached take profit, na = none. type NocOrder string side string otype float qty float price float stopPrice float sl float tp // @type What the copier has been told. Create ONE per script with noc_new() and keep it in a var. // @field token The source token from New Order Copier (Edit Source of the TradingView source). // @field qtyUnit "contracts" or "lots" - how the copier scales qty (mapping table). // @field seq Message counter. // @field orders The live orders by oid. type NocBook string token string qtyUnit int seq = 0 map orders noc_num(float x) => na(x) ? "null" : str.tostring(x, "#.##########") noc_changed(float was, float now) => na(was) != na(now) or (not na(was) and math.abs(was - now) > syminfo.mintick * 0.5) noc_head(NocBook b, string msg) => b.seq += 1 '{"v":1,"token":"' + b.token + '","msg":"' + msg + '","id":' + str.tostring(b.seq) + ',"ts":"' + str.format_time(timenow, "yyyy-MM-dd'T'HH:mm:ss'Z'", "UTC") + '"' // @function Creates the NocBook. Keep it: `var NocBook book = noc_new(token)`. Read the token with `input.string("", "New Order Copier token (TV-...)", display = display.none)` - it is a secret and must not show in the chart legend. // @param token The source token (TV-...). // @param qtyUnit "contracts" (default): qty goes to the broker as it is (1 = 1 contract / share / CFD unit at Interactive Brokers, 1 = 1 LOT at MetaTrader); only the connector's multiplier scales it. "lots": the mapping table's factor converts qty first. // @returns A new NocBook. noc_new(string token, string qtyUnit = "contracts") => NocBook.new(token, qtyUnit, 0, map.new()) // @function States an order. Call it on every bar while the order should exist (or at least whenever it changes): the first real-time call PLACES it, a later call with other prices / qty / sl / tp MODIFIES it, an unchanged call sends nothing. Side and type of a placed oid cannot change - use a new oid. // @param b The NocBook. // @param oid Your order id, unique per source (e.g. "L1"); at most 64 characters. // @param buy true = BUY, false = SELL. // @param otype "MKT", "LMT", "STP" or "STPLMT". // @param qty Quantity (> 0). // @param price Limit price for LMT and STPLMT. STPLMT into a MetaTrader account: a BUY stop limit's limit must be BELOW its trigger, a SELL's above (MetaTrader refuses it otherwise, "Invalid price"); Interactive Brokers takes either. // @param stopPrice Trigger price for STP and STPLMT. // @param sl Attached stop loss (optional). // @param tp Attached take profit (optional). // @returns The alert text, or "". noc_order(NocBook b, string oid, bool buy, string otype, float qty, float price = na, float stopPrice = na, float sl = na, float tp = na) => string msg = "" if barstate.isrealtime NocOrder o = b.orders.get(oid) string side = buy ? "BUY" : "SELL" if na(o) b.orders.put(oid, NocOrder.new(side, otype, qty, price, stopPrice, sl, tp)) msg := noc_head(b, "place") + ',"oid":"' + oid + '","symbol":"' + syminfo.ticker + '","side":"' + side + '","type":"' + otype + '","qty":' + noc_num(qty) + ',"qty_unit":"' + b.qtyUnit + '"' if not na(price) msg += ',"price":' + noc_num(price) if not na(stopPrice) msg += ',"stop_price":' + noc_num(stopPrice) if not na(sl) msg += ',"sl":' + noc_num(sl) if not na(tp) msg += ',"tp":' + noc_num(tp) if otype == "MKT" msg += ',"ref_price":' + noc_num(close) msg += "}" else string d = "" if noc_changed(o.price, price) d += ',"price":' + noc_num(price) o.price := price if noc_changed(o.stopPrice, stopPrice) d += ',"stop_price":' + noc_num(stopPrice) o.stopPrice := stopPrice if noc_changed(o.qty, qty) d += ',"qty":' + noc_num(qty) o.qty := qty if noc_changed(o.sl, sl) d += ',"sl":' + noc_num(sl) o.sl := sl if noc_changed(o.tp, tp) d += ',"tp":' + noc_num(tp) o.tp := tp if d != "" msg := noc_head(b, "modify") + ',"oid":"' + oid + '"' + d + "}" msg // @function Cancels an order: withdraws what still rests and closes what of it filled, its stop loss / take profit go with it. // @param b The NocBook. // @param oid The order id. // @returns The alert text, or "" (unknown oid, historical bar). noc_cancel(NocBook b, string oid) => string msg = "" if barstate.isrealtime and b.orders.contains(oid) b.orders.remove(oid) msg := noc_head(b, "cancel") + ',"oid":"' + oid + '"}' msg // @function Closes the position an order opened (market) and withdraws its rest and its stop loss / take profit. // @param b The NocBook. // @param oid The order id. // @returns The alert text, or "". noc_closeOrder(NocBook b, string oid) => string msg = "" if barstate.isrealtime and b.orders.contains(oid) b.orders.remove(oid) msg := noc_head(b, "close") + ',"oid":"' + oid + '","ref_price":' + noc_num(close) + '}' msg // @function Closes everything of this source on the chart's symbol: every resting order is withdrawn, every position closed. // @param b The NocBook. // @returns The alert text, or "". noc_closeAll(NocBook b) => string msg = "" if barstate.isrealtime b.orders.clear() msg := noc_head(b, "close") + ',"symbol":"' + syminfo.ticker + '","ref_price":' + noc_num(close) + '}' msg // @function Forgets an order WITHOUT telling the copier - for an order that has ended at the broker by itself (filled entry whose stop loss / take profit closed it), so its oid can be stated again. // @param b The NocBook. // @param oid The order id. // @returns true when the oid was known. noc_forget(NocBook b, string oid) => bool had = b.orders.contains(oid) if had b.orders.remove(oid) had // ===== NOC functions END ===== // display.none: the token is a secret - never in the chart legend / status line string token = input.string("", "New Order Copier token (TV-...)", display = display.none) string unit = input.string("contracts", "Quantity unit", options = ["contracts", "lots"]) float qty = input.float(1.0, "Quantity", minval = 0.0001) int every = input.int(2, "Bars per step", minval = 1) var NocBook book = noc_new(token, unit) send(string m) => if m != "" alert(m, alert.freq_all) float a = ta.atr(14) // steps count from the first real-time bar; nothing happens on history var int t0 = na if barstate.isrealtime and na(t0) t0 := bar_index int n = na(t0) ? -1 : bar_index - t0 bool stepBar = n >= 0 and n % every == 0 int k = n >= 0 ? int(math.floor(n / every)) : 0 int step = stepBar ? k % 12 : -1 int cycle = int(math.floor(k / 12)) var float p = na var float sp = na var float sl = na var float tp = na var string oid = "" if step == 0 // LIMIT buy, 3 ATR below oid := "LMT" + str.tostring(cycle) sp := na p := close - 3 * a sl := p - 2 * a tp := p + 3 * a strategy.entry(oid, strategy.long, qty, limit = p) strategy.exit(oid + "x", oid, stop = sl, limit = tp) send(noc_order(book, oid, true, "LMT", qty, price = p, sl = sl, tp = tp)) else if step == 1 // move it 1 ATR lower, SL/TP with it p -= a sl -= a tp -= a strategy.entry(oid, strategy.long, qty, limit = p) strategy.exit(oid + "x", oid, stop = sl, limit = tp) send(noc_order(book, oid, true, "LMT", qty, price = p, sl = sl, tp = tp)) else if step == 2 strategy.cancel(oid) strategy.cancel(oid + "x") send(noc_cancel(book, oid)) else if step == 3 // STOP sell, 3 ATR below oid := "STP" + str.tostring(cycle) p := na sp := close - 3 * a sl := sp + 2 * a tp := sp - 3 * a strategy.entry(oid, strategy.short, qty, stop = sp) strategy.exit(oid + "x", oid, stop = sl, limit = tp) send(noc_order(book, oid, false, "STP", qty, stopPrice = sp, sl = sl, tp = tp)) else if step == 4 // trigger 1 ATR lower, SL/TP with it sp -= a sl -= a tp -= a strategy.entry(oid, strategy.short, qty, stop = sp) strategy.exit(oid + "x", oid, stop = sl, limit = tp) send(noc_order(book, oid, false, "STP", qty, stopPrice = sp, sl = sl, tp = tp)) else if step == 5 strategy.cancel(oid) strategy.cancel(oid + "x") send(noc_cancel(book, oid)) else if step == 6 // STOP LIMIT buy, trigger 3 ATR above, limit 0.5 ATR above it oid := "SLM" + str.tostring(cycle) sp := close + 3 * a p := sp + 0.5 * a sl := sp - 2 * a tp := sp + 3 * a strategy.entry(oid, strategy.long, qty, limit = p, stop = sp) strategy.exit(oid + "x", oid, stop = sl, limit = tp) send(noc_order(book, oid, true, "STPLMT", qty, price = p, stopPrice = sp, sl = sl, tp = tp)) else if step == 7 // 1 ATR higher sp += a p += a sl += a tp += a strategy.entry(oid, strategy.long, qty, limit = p, stop = sp) strategy.exit(oid + "x", oid, stop = sl, limit = tp) send(noc_order(book, oid, true, "STPLMT", qty, price = p, stopPrice = sp, sl = sl, tp = tp)) else if step == 8 strategy.cancel(oid) strategy.cancel(oid + "x") send(noc_cancel(book, oid)) else if step == 9 // MARKET buy with SL/TP 2 ATR away oid := "MKT" + str.tostring(cycle) p := na sp := na sl := close - 2 * a tp := close + 2 * a strategy.entry(oid, strategy.long, qty) strategy.exit(oid + "x", oid, stop = sl, limit = tp) send(noc_order(book, oid, true, "MKT", qty, sl = sl, tp = tp)) else if step == 10 // SL to 1 ATR below, TP 1 ATR further sl := close - a tp += a strategy.exit(oid + "x", oid, stop = sl, limit = tp) send(noc_order(book, oid, true, "MKT", qty, sl = sl, tp = tp)) else if step == 11 strategy.close(oid) send(noc_closeOrder(book, oid)) // the levels of the order the demo is working on plot(p, "limit", color.blue, style = plot.style_linebr) plot(sp, "stop", color.orange, style = plot.style_linebr) plot(sl, "stop loss", color.red, style = plot.style_linebr) plot(tp, "take profit", color.green, style = plot.style_linebr)