At the intersection of MA 10 and MA 25 (the periods are specified in the settings), this algorithm opens a new deal on BUY or closes if there is one.
export class Main extends TradingBot {
constructor() {
super();
this.setProperty(Property.Digits, 2);
this.addInput('period1', InputType.int, 10, { min: 2 }, { max: 500 });
this.addInput('period2', InputType.int, 25, { min: 2 }, { max: 500 });
this.addInput('averaging', InputType.Averaging, Averaging.Simple);
this.addInput('appliedPrice', InputType.AppliedPrice, AppliedPrice.Close);
this.addInput('priceType', InputType.PriceType, PriceType.Bid);
}
onInit() {}
/**
* Trade search method
*/
async getLastOpenOrder() {
let orders = await Order.all(Order.Source.Trades);
orders = orders.filter(
(order) => order.Symbol === Current.Symbol && order.UserData === Current.ScriptId
).sort(
(a, b) => b.OpenTime - a.OpenTime
);
return orders.length ? orders[0] : null;
}
async onTick() {
const {
period1,
period2,
averaging,
appliedPrice,
priceType,
} = this.getInputs();
// First MA indicator data
const list1 = await Indicators.MA(
Current.Symbol,
Current.TimeFrame,
period1,
0,
averaging,
appliedPrice,
priceType
);
// Data of the second indicator MA
const list2 = await Indicators.MA(
Current.Symbol,
Current.TimeFrame,
period2,
0,
averaging,
appliedPrice,
priceType
);
// If the MA indicator lines cross
if (list1[0].toFixed(Current.Digits) === list2[0].toFixed(Current.Digits)) {
// Find the last deal opened by this indicator
const order = await this.getLastOpenOrder();
if (order) {
// Check that the deal was opened in another bar of the minute timeframe
const sameBar = Bar.sameBar(order.OpenTime, Current.Time, TimeFrame.M1);
if (!sameBar) {
// Closing the deal
await order.close();
}
} else {
// We take the minimum amount of a symbol
const volume = Market.info(Market.Mode.VolumeMin, Current.Symbol);
// Create a deal
const newOrder = new Order(Current.Symbol, Order.TradeCmd.Buy, volume);
// We set user data by which we will search for a deal in the future
newOrder.setUserData(Current.ScriptId);
// Save changes (open a deal)
await newOrder.save();
}
}
}
}