Input parameters
defaultInstrument: CHF/JPY - instrument used
defaultTradeAmount: 5.0 - amount used in position size calculation
defaultSlippage: 5 - maximum allowed slippage in pips
defaultStopLoss: 233 - stop loss in pips
defaultTakeProfit: 1777 - take profit in pips
defaultPeriod: Hourly - period
maxSpread: 3.0 - maximum allowed spread in pips
maPeriod: 2 - time period of daily exponential moving average (ema)
adjustRatio: 0.95 - used in position size calculation formula
adjustPips: 10.0 - number of pips after which to recalculate position size
Trading logic
1. Starts execution in onCandle event handler. Continues only if candle instrument equals defaultInstrument and candle period equals defaultPeriod.
2. Calculates spread and compares it to maxSpread. Continues only if spread is lower than maxSpread. This filters out unfavorable trading conditions.
3. Checks number of positions.
3.a If there are no positions it calculates two values from daily ema (with time period maPeriod, based on closing prices). First is for two days back, second for one day back.
If account equity is lower than 99K, it inverts adjustRatio to more than 1. Conversely, if account equity is greater than 99K and adjustRatio is greater than 1, adjustRatio is inverted to less than 1.
It resets tradeNum to zero.
It calculates and validates initial position size: min (defaultTradeAmount * 1.5, equity / 13333).
It compares first ema value with the second and opens short position if the first is greater than the second or long position otherwise. Position is opened using:
- defaultInstrument
- calculated position size
- defaultSlippage
- defaultStopLoss
- defaultTakeProfit
It increases tradeNum by 1.
3.b If there are positions, it checks if there are open (filled) positions. If there are (assuming no bugs, this means one open position), it checks position profit. If position profit is greater than adjustPips, it continues execution.
It saves position stop loss and take profit prices to sl and tp variables.
It calculates position size with the following formula: defaultTradeAmount * adjustRatio ^ tradeNum + defaultTradeAmount / (tradeNum + 2), where tradeNum is number of the trade in given position. Usually it decreases position size gradually, while running towards the target and possibility of reversal rises (when adjustRatio is less than 1). It can also gradually increase position size when account equity falls below 99K and more risky approach is used (adjustRatio is more than 1).
It updates (tightens) sl by as much as position moved in profit.
It closes position and then reopens it, using:
- defaultInstrument
- recalculated position size
- defaultSlippage
- sl (updated)
- tp (same as initial)
It increases tradeNum by 1.