— Function to calculate the simple moving average function sma(period, data) local sum = 0 for i = 1, period do sum = sum + data[i] end return sum / period end — Define the two moving average periods shortPeriod = 10 longPeriod = 50 — Define the stop loss and take profit levels stopLoss = -5 takeProfit = 10 — Initialize the moving average arrays shortMA = {} longMA = {} — Loop through the data to calculate the moving averages for i = 1, #data do — Calculate the short moving average if i >= shortPeriod then shortMA[i] = sma(shortPeriod, data[i — shortPeriod + 1, i]) end — Calculate the long moving average if i >= longPeriod then longMA[i] = sma(longPeriod, data[i — longPeriod + 1, i]) end — Check if a trade should be opened if shortMA[i] and longMA[i] and shortMA[i] > longMA[i] then — Buy the asset position = «long» — Set the stop loss and take profit levels stopLossPrice = data[i] * (1 + stopLoss / 100) takeProfitPrice = data[i] * (1 + takeProfit / 100) end — Check if the stop loss or take profit levels have been reached if position == «long» then if data[i] <= stopLossPrice then — Sell the asset to exit the trade position = nil end if data[i] >= takeProfitPrice then — Sell the asset to exit the trade position = nil end end end
— Function to calculate the simple moving average
function sma(period, data)
local sum = 0
for i = 1, period do
sum = sum + data[i]
end
return sum / period
end
— Define the two moving average periods
shortPeriod = 10
longPeriod = 50
— Define the stop loss and take profit levels
stopLoss = -5
takeProfit = 10
— Initialize the moving average arrays
shortMA = {}
longMA = {}
— Loop through the data to calculate the moving averages
for i = 1, #data do
— Calculate the short moving average
if i >= shortPeriod then
shortMA[i] = sma(shortPeriod, data[i — shortPeriod + 1, i])
end
— Calculate the long moving average
if i >= longPeriod then
longMA[i] = sma(longPeriod, data[i — longPeriod + 1, i])
end
— Check if a trade should be opened
if shortMA[i] and longMA[i] and shortMA[i] > longMA[i] then
— Buy the asset
position = «long»
— Set the stop loss and take profit levels
stopLossPrice = data[i] * (1 + stopLoss / 100)
takeProfitPrice = data[i] * (1 + takeProfit / 100)
end
— Check if the stop loss or take profit levels have been reached
if position == «long» then
if data[i] <= stopLossPrice then
— Sell the asset to exit the trade
position = nil
end
if data[i] >= takeProfitPrice then
— Sell the asset to exit the trade
position = nil
end
end
end
Стратегия на II квартал 2026 года. Акции с высокими дивидендами
Алексей Девятов Аналитики Альфа-Инвестиций представили инвестиционную стратегию на II квартал 2026 года : прогнозы для российской экономики и отдельных отраслей, актуальные тренды и наиболее...
Мы заставили ИИ-модели торговать на бирже. И вот что из этого вышло
Могут ли языковые модели торговать на бирже — и не слить, а реально заработать? «Финам» завершил первый этап «Финам Арены» — эксперимента, в котором шесть ведущих языковых моделей...
Металлы растут в ожидании окончания иранского конфликта
Золото в ходе торгов 8 апреля выросло в цене на 2%, до $4788 за тройскую унцию, и продолжает двигаться вверх. В последние дни в его котировках наблюдалась повышенная волатильность, и до локального...
Астра: где зарыты кроты в отчете 2025? Сравнение с BAZA, DATA, DIAS, IVAT
На прошлой неделе компания Астра представила отчет за 2025 год: ✅ отчет МСФО 2025 ✅ презентация ✅ пресс-релиз В этой заметке мы разберем: 👉насколько инвест привлекательна Астра по текущим...
Елена Федорова,
1. «Хотите помочь?» — Нет;
2. «Хотите присоединиться?» — нет;
3. «Может подскажете?» — Нет.
Я задал простой вопрос: вы подавали заявление в СК? Я предполагал, что вы отв...
Металлы растут в ожидании окончания иранского конфликта Золото в ходе торгов 8 апреля выросло в цене на 2%, до $4788 за тройскую унцию, и продолжает двигаться вверх. В последние дни в его котировках н...
Ну что, любители посидеть на планке, продолжаете верить и надеяться? Это больше не инвестиционный инструмент, перекидывайте эту горячую картошку, раз нравится.
Стройка рухнула, металлургия в кризисе, но главная проблема в России – телеграм
Вчера вышли данные по стройке и металлургии. Ребята, это полный кабздец. Для понимания масштаба просто цифры.
За...
Стройка рухнула, металлургия в кризисе, но главная проблема в России – телеграм
Вчера вышли данные по стройке и металлургии. Ребята, это полный кабздец. Для понимания масштаба просто цифры.
За...
ПАРУС-ТРИУМФ: итоги голосования! Друзья, привет! 👋 📣 До 1 апреля мы проводили голосование по фонду «ПАРУС-ТРИУМФ»! ❗️На повестке — продление срока действия фонда до 49 лет. 🔥 Рады подвести итоги:65% о...
ПАРУС-ТРИУМФ: итоги голосования! Друзья, привет! 👋 📣 До 1 апреля мы проводили голосование по фонду «ПАРУС-ТРИУМФ»! ❗️На повестке — продление срока действия фонда до 49 лет. 🔥 Рады подвести итоги:65% о...
DollarBill, Работяга, скорее всего прибыль теперь не выгодно будет показывать даже за 2025 год. Потому что рефинансирование тела долга и его обслуживани...
DollarBill, всегда докупаю что падает ч...
Принцип прост, некое количество пунктов от позиции.
Вот лови:
— Function to calculate the simple moving average function sma(period, data) local sum = 0 for i = 1, period do sum = sum + data[i] end return sum / period end — Define the two moving average periods shortPeriod = 10 longPeriod = 50 — Define the stop loss and take profit levels stopLoss = -5 takeProfit = 10 — Initialize the moving average arrays shortMA = {} longMA = {} — Loop through the data to calculate the moving averages for i = 1, #data do — Calculate the short moving average if i >= shortPeriod then shortMA[i] = sma(shortPeriod, data[i — shortPeriod + 1, i]) end — Calculate the long moving average if i >= longPeriod then longMA[i] = sma(longPeriod, data[i — longPeriod + 1, i]) end — Check if a trade should be opened if shortMA[i] and longMA[i] and shortMA[i] > longMA[i] then — Buy the asset position = «long» — Set the stop loss and take profit levels stopLossPrice = data[i] * (1 + stopLoss / 100) takeProfitPrice = data[i] * (1 + takeProfit / 100) end — Check if the stop loss or take profit levels have been reached if position == «long» then if data[i] <= stopLossPrice then — Sell the asset to exit the trade position = nil end if data[i] >= takeProfitPrice then — Sell the asset to exit the trade position = nil end end end
— Function to calculate the simple moving average
function sma(period, data)
local sum = 0
for i = 1, period do
sum = sum + data[i]
end
return sum / period
end
— Define the two moving average periods
shortPeriod = 10
longPeriod = 50
— Define the stop loss and take profit levels
stopLoss = -5
takeProfit = 10
— Initialize the moving average arrays
shortMA = {}
longMA = {}
— Loop through the data to calculate the moving averages
for i = 1, #data do
— Calculate the short moving average
if i >= shortPeriod then
shortMA[i] = sma(shortPeriod, data[i — shortPeriod + 1, i])
end
— Calculate the long moving average
if i >= longPeriod then
longMA[i] = sma(longPeriod, data[i — longPeriod + 1, i])
end
— Check if a trade should be opened
if shortMA[i] and longMA[i] and shortMA[i] > longMA[i] then
— Buy the asset
position = «long»
— Set the stop loss and take profit levels
stopLossPrice = data[i] * (1 + stopLoss / 100)
takeProfitPrice = data[i] * (1 + takeProfit / 100)
end
— Check if the stop loss or take profit levels have been reached
if position == «long» then
if data[i] <= stopLossPrice then
— Sell the asset to exit the trade
position = nil
end
if data[i] >= takeProfitPrice then
— Sell the asset to exit the trade
position = nil
end
end
end