Input parameters
defaultInstrument: NZD/JPY - instrument used
defaultTradeAmount: 3.5 - amount used in position size calculation
defaultSlippage: 5 - maximum allowed slippage in pips
defaultStopLoss: 233 - stop loss in pips
defaultTakeProfit: 977 - take profit in pips
defaultPeriod: 1 Min - period
closePosition: true - close open position
maxSpread: 4.0 - maximum allowed spread in pips
maPeriod: 2 - time period of H4 exponential moving average (ema)
adjustRatio: 0.99 - used in position size calculation formula
adjustPips: 7.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 H4 ema
(with time period maPeriod, based on closing prices). First is for
two
H4 periods back, second for one H4 period back.
It resets tradeNum to zero.
It sets amount to defaultTradeAmount.
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
- amount
- defaultSlippage
- defaultStopLoss
- defaultTakeProfit
It increases tradeNum by 1.
3.b If there are positions, it checks if there are open (filled)
positions.
If closePosition is true, it closes open position, resets
closePosition to false and returns.
If there are open positions (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: amount *
adjustRatio. It decreases position size gradually, while running
towards the target and possibility of reversal rises.
It updates (tightens) sl by as much as position moved in profit.
It closes position and then reopens it, using:
- defaultInstrument
- amount (updated)
- defaultSlippage
- sl (updated)
- tp (same as initial)
It increases tradeNum by 1.