JavaScript Strategy Reference
Strategy Event Functions
onStrategyStart
Called before the strategy is started, the onStrategyStart function is where your code creates new objects and attaches them to variable declarations.
var sma; // simple moving average variable var smaLength = 7; // length of moving average function onStrategyStart() { sma = new SMA(smaLength); }
onBarOpen
Called before every bar is received by your strategy. The purpose of onBarOpen is to give you a chance to do something on the leading edge of a bar, before the bar has been created.
onBar
Called when the market data provider sends a completed bar. Each bar contains open, high, low, close and volume properties for the past bar interval. The onBar function is called on the trailing edge of the current bar, if you need to take actions on the leading edge of the next bar, use the onBarOpen function.
onPositionOpened
Called when a new position is established as a result of a completed trade.
onPositionChanged
Called whenever the size of a position is changed, one way or the other, as a result of a completed trade.
onPositionClosed
Called whenever the size of a position becomes zero, as a result of a completed trade.
How to place orders
Here are short code fragments that show how to place typical trading orders to buy/sell long, and to sell/cover short. To sell and cover short, reverse the sequence of the buy/sell orders.
Sell at market price:
var order; order = new MarketOrder(Sell, qty); order.text = 'Text to show in the trade log'; order.send();
Buy at limit price:
var order; order = new LimitOrder(Buy, qty, prevClose); order.text = 'MyStrategy - Buy'; order.send();
Place a stop-loss order using trade events:
var stopLossEnabled; var stopLimit; function onTrade(trade) { if (hasPosition()) { if (stopLossEnabled && trade.price < stopLimit) { order = new MarketOrder(Sell, qty); order.text = 'Stop Loss'; order.send(); stopLossEnabled = false; } } }
