在MA 10和MA 25的交点(在设置中指定了周期),此算法将对BUY进行新的交易,如果有则关闭。
export class Main extends Algorithm {
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() {}
/**
* 贸易搜索方法
*/
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();
// 第一MA指标数据
const list1 = await Indicators.MA(
Current.Symbol,
Current.TimeFrame,
period1,
0,
averaging,
appliedPrice,
priceType
);
// 第二指标MA的数据
const list2 = await Indicators.MA(
Current.Symbol,
Current.TimeFrame,
period2,
0,
averaging,
appliedPrice,
priceType
);
// 如果MA指标线交叉
if (list1[0].toFixed(Current.Digits) === list2[0].toFixed(Current.Digits)) {
// 查找此指标打开的最后一笔交易
const order = await this.getLastOpenOrder();
if (order) {
// 检查是否在分钟内的另一个栏中打开了交易
const sameBar = Bar.sameBar(order.OpenTime, Current.Time, TimeFrame.M1);
if (!sameBar) {
// 完成交易
await order.close();
}
} else {
// 我们以最小数量的符号
const volume = Market.info(Market.Mode.VolumeMin, Current.Symbol);
// 建立交易
const newOrder = new Order(Current.Symbol, Order.TradeCmd.Buy, volume);
// 我们设置用户数据,以供将来搜索交易时使用
newOrder.setUserData(Current.ScriptId);
// 保存更改(打开交易)
await newOrder.save();
}
}
}
}