Back to Strategies
EMA Crossover Trend Follower
Code Strategy by 0xsDp5JzBDn·2026-07-02
// Env: FAST_EMA, SLOW_EMA, INTERVAL, TP_PERCENT, SL_PERCENT
async function getCloses(interval, limit) {
const res = await $.Http.get("https://fapi.binance.com/fapi/v1/klines", {
symbol: $.Price.symbol,
interval,
limit
});
if (res.status !== 200) return null;
const raw = JSON.parse(res.text);
return raw.map(c => parseFloat(c[4])); // Close prices
}
const FAST_EMA = Number($.Env.FAST_EMA || 9);
const SLOW_EMA = Number($.Env.SLOW_EMA || 21);
const INTERVAL = $.Env.INTERVAL || "15m";
const TP_PERCENT = Number($.Env.TP_PERCENT || 1.5);
const SL_PERCENT = Number($.Env.SL_PERCENT || 1.0);
let S = (await $.Storage.get()) || { position: null, entryPrice: null };
let nextAction = null;
// 1) Manage an existing position first
if (S.position) {
const roi = $.Strategy.roi(true, S.entryPrice, $.Price.price);
if (roi !== null) {
const profit = S.position === "LONG" ? roi : -roi; // shorts invert sign
if (profit >= TP_PERCENT || profit <= -SL_PERCENT) {
nextAction = { type: $.Action.EXIT };
}
}
}
// 2) Otherwise look for entries / crossover exits
if (!nextAction) {
const closes = await getCloses(INTERVAL, Math.max(SLOW_EMA * 3, 60));
if (closes && closes.length > SLOW_EMA) {
const fast = new $.Ta.EMA(FAST_EMA);
const slow = new $.Ta.EMA(SLOW_EMA);
for (const c of closes) {
fast.update(c);
slow.update(c);
}
if (fast.isStable && slow.isStable) {
const bullish = fast.getResult() > slow.getResult();
if (!S.position && bullish) {
nextAction = { type: $.Action.LONG, side: "LONG" };
} else if (!S.position && !bullish) {
nextAction = { type: $.Action.SHORT, side: "SHORT" };
} else if (S.position === "LONG" && !bullish) {
nextAction = { type: $.Action.EXIT };
} else if (S.position === "SHORT" && bullish) {
nextAction = { type: $.Action.EXIT };
}
}
}
}
if (nextAction) {
await $.Strategy.action(nextAction.type);
if (nextAction.type === $.Action.EXIT) {
S.position = null;
S.entryPrice = null;
} else {
S.position = nextAction.side;
S.entryPrice = $.Price.price;
}
}
await $.Storage.set(S);