Всем добрый вечер. Мне 14, я пишу своему отцу пару скриптов, чтобы ему было удобнее работать в терминале. В этом скрипте должна быть реализована стратегия FiBo, вроде бы она довольно известная.
Суть в том что при увеличении цены срабатывает функция CheckLine, где я сравниваю строки в csv файле, состоящем из цен, по которым я покупал когда либо инструмент.
При покупке он должен записывать туда цену, при продаже вычеркивать одну из цен, ориентируясь на которую он продал.
Казус в том, что ничего из прошлой написанной мною строки он не делает. Память по просту не работает!
Я пишу скрипты на Qlua недолго, иногда использую ИИ (Извините меня все, я сам против вайбкодинга, но мне батя узкие сроки ставит). Помогите пожалуйста!!!!
Если есть любые другие замечания пишите.
Сам скрипт:
function OnInit()
--Настройки, изменять при надобности.--
class = "QJSIM" -- Тип интсрумента
sec = "SBER" -- Код интсрумента
account = "NL0011100043" -- Номер аккаунта, тут всё понятно
LotSize = 1 -- Кол-во лотов в заявке.
step = 0.02 -- Шаг цены.
limits = 10 -- Лимит торговли
tid = 0 -- Не трогать!
trz_comment = "FIBO-2 --> " -- Не трогать.
price = nil -- Не трогать.
uprice = nil
dprice = nil
SellPrice = nil
TradeNums = {}
Trades[]
CSV = io.open(getScriptPath().."/FiboTrades.csv", "a+");
secondfile = "fibobuys.csv"
end
function CheckLine(number)
current_line = 0
same = 0;
ss = 0
local CheckFile = io.open(secondfile, "r");
for line in CheckFile:lines() do
if tonumber(line) == number then same = same+1; end
if tonumber(line) <= number then LimitSpot('S', number); break end;
current_line = current_line + 1
end
elseif same == 0 and climits ~= limits then LimitSpot('B', number) end
CheckFile:close();
end
function LimitSpot(operation, SpotPrice)
tid = tid+1
transaction={
["TRANS_ID"]=tostring(tid),
["ACTION"]="NEW_ORDER",
["CLASSCODE"]=class,
["SECCODE"]=sec,
["OPERATION"]=operation,
["QUANTITY"]=tostring(LotSize),
["PRICE"]=tostring(SpotPrice),
["ACCOUNT"]=tostring(account),
["EXECUTION_CONDITION"]="PUT_IN_QUEUE", -- тип заявки лимитная
}
res = sendTransaction(transaction)
if res ~= '' then
message(trz_comment..'Transaction Error! '..res)
else
message(trz_comment..'Transaction Success! ID = '..tid)
end
end
function math_round( roundIn , roundDig ) -- первый аргумент число для округления, второй - количество знаков после запятой
local mul = 10^roundDig
return ( math.floor( ( roundIn * mul ) + 0.5 )/mul )
end
function main()
message(trz_comment..'Start.')
climits = 0
do_main = true
while do_main do
sleep(1000)
end
end
function OnParam(class1, sec1)
if class1 == class and sec1 == sec then
price = math_round(getParamEx(class, sec, "last").param_value, 2)
if uprice ~= nil then
if price <= dprice then
dprice = dprice-step
uprice = uprice-step
message(trz_comment..'Price-- -> '..price)
else if price >= uprice then
CheckLine(price);
dprice = dprice+step
uprice = uprice+step
message(trz_comment.."Price++ -> "..price)
end
end
end
end
end
function OnTrade(trade)
if trade.sec_code == sec and trade.class_code == class then
if uprice == nil then
uprice = trade.price + step
dprice = trade.price - step
message(trz_comment..'Grid placed success!')
end
t = bit.band(tonumber(trade['flags']),4) -- 1 = sell 0 = buy
if t == 0 then message(trz_comment.."buy "..trade.price); Op = "Buy"; climits = climits + 1;
wr = io.open(secondfile, 'a+')
wr:write(trade.price.."\n");
wr:flush();
wr:close();
else message(trz_comment.."Sell "..trade.price); climits = climits - 1; Op = "Sell"; SellPrice = nil;
remove_line_from_csv(secondfile, current_line)
end
for i=#TradeNums,1,-1 do
-- Если данная сделка уже была записана, выходит из функции
if TradeNums[i] == trade.trade_num then return; end;
end;
-- Если мы здесь, значит сделка не была найдена в числе уже записанных
-- Добавляет в массив номер новой сделки
TradeNums[#TradeNums + 1] = trade.trade_num;
-- Вычисляет операцию сделки
-- Создает строку сделки для записи в файл ("Дата и время;Код класса;Код бумаги;Номер сделки;Номер заявки;Операция;Цена;Количество\n")
local TradeLine = os.date("%c", os.time(trade.datetime))..";"..
trade.class_code..";"..
trade.sec_code..";"..
trade.trade_num..";"..
trade.order_num..";"..
Op..";"..
trade.price..";"..
trade.qty.."\n";
-- Записывает строку в файл
CSV:write(TradeLine);
-- Сохраняет изменения в файле
CSV:flush();
end
end
function remove_line_from_csv(filename, line_to_remove)
local input_file = io.open(filename, "r")
if not input_file then
print("Ошибка открытия файла для чтения")
return false
end
local temp_filename = filename .. ".tmp"
local output_file = io.open(temp_filename, "w")
if not output_file then
print("Ошибка открытия временного файла для записи")
input_file:close()
return false
end
local line_number = 1
for line in input_file:lines() do
if line_number ~= line_to_remove then
output_file:write(line .. "\n")
end
line_number = line_number + 1
end
input_file:close()
output_file:close()
-- Удаляем старый файл и переименовываем временный
os.remove(filename)
os.rename(temp_filename, filename)
message("deleted")
end
Суть в том что при увеличении цены срабатывает функция CheckLine, где я сравниваю строки в csv файле, состоящем из цен, по которым я покупал когда либо инструмент.
При покупке он должен записывать туда цену, при продаже вычеркивать одну из цен, ориентируясь на которую он продал.
Казус в том, что ничего из прошлой написанной мною строки он не делает. Память по просту не работает!
Я пишу скрипты на Qlua недолго, иногда использую ИИ (Извините меня все, я сам против вайбкодинга, но мне батя узкие сроки ставит). Помогите пожалуйста!!!!
Если есть любые другие замечания пишите.
Сам скрипт:
function OnInit()
--Настройки, изменять при надобности.--
class = "QJSIM" -- Тип интсрумента
sec = "SBER" -- Код интсрумента
account = "NL0011100043" -- Номер аккаунта, тут всё понятно
LotSize = 1 -- Кол-во лотов в заявке.
step = 0.02 -- Шаг цены.
limits = 10 -- Лимит торговли
tid = 0 -- Не трогать!
trz_comment = "FIBO-2 --> " -- Не трогать.
price = nil -- Не трогать.
uprice = nil
dprice = nil
SellPrice = nil
TradeNums = {}
Trades[]
CSV = io.open(getScriptPath().."/FiboTrades.csv", "a+");
secondfile = "fibobuys.csv"
end
function CheckLine(number)
current_line = 0
same = 0;
ss = 0
local CheckFile = io.open(secondfile, "r");
for line in CheckFile:lines() do
if tonumber(line) == number then same = same+1; end
if tonumber(line) <= number then LimitSpot('S', number); break end;
current_line = current_line + 1
end
elseif same == 0 and climits ~= limits then LimitSpot('B', number) end
CheckFile:close();
end
function LimitSpot(operation, SpotPrice)
tid = tid+1
transaction={
["TRANS_ID"]=tostring(tid),
["ACTION"]="NEW_ORDER",
["CLASSCODE"]=class,
["SECCODE"]=sec,
["OPERATION"]=operation,
["QUANTITY"]=tostring(LotSize),
["PRICE"]=tostring(SpotPrice),
["ACCOUNT"]=tostring(account),
["EXECUTION_CONDITION"]="PUT_IN_QUEUE", -- тип заявки лимитная
}
res = sendTransaction(transaction)
if res ~= '' then
message(trz_comment..'Transaction Error! '..res)
else
message(trz_comment..'Transaction Success! ID = '..tid)
end
end
function math_round( roundIn , roundDig ) -- первый аргумент число для округления, второй - количество знаков после запятой
local mul = 10^roundDig
return ( math.floor( ( roundIn * mul ) + 0.5 )/mul )
end
function main()
message(trz_comment..'Start.')
climits = 0
do_main = true
while do_main do
sleep(1000)
end
end
function OnParam(class1, sec1)
if class1 == class and sec1 == sec then
price = math_round(getParamEx(class, sec, "last").param_value, 2)
if uprice ~= nil then
if price <= dprice then
dprice = dprice-step
uprice = uprice-step
message(trz_comment..'Price-- -> '..price)
else if price >= uprice then
CheckLine(price);
dprice = dprice+step
uprice = uprice+step
message(trz_comment.."Price++ -> "..price)
end
end
end
end
end
function OnTrade(trade)
if trade.sec_code == sec and trade.class_code == class then
if uprice == nil then
uprice = trade.price + step
dprice = trade.price - step
message(trz_comment..'Grid placed success!')
end
t = bit.band(tonumber(trade['flags']),4) -- 1 = sell 0 = buy
if t == 0 then message(trz_comment.."buy "..trade.price); Op = "Buy"; climits = climits + 1;
wr = io.open(secondfile, 'a+')
wr:write(trade.price.."\n");
wr:flush();
wr:close();
else message(trz_comment.."Sell "..trade.price); climits = climits - 1; Op = "Sell"; SellPrice = nil;
remove_line_from_csv(secondfile, current_line)
end
for i=#TradeNums,1,-1 do
-- Если данная сделка уже была записана, выходит из функции
if TradeNums[i] == trade.trade_num then return; end;
end;
-- Если мы здесь, значит сделка не была найдена в числе уже записанных
-- Добавляет в массив номер новой сделки
TradeNums[#TradeNums + 1] = trade.trade_num;
-- Вычисляет операцию сделки
-- Создает строку сделки для записи в файл ("Дата и время;Код класса;Код бумаги;Номер сделки;Номер заявки;Операция;Цена;Количество\n")
local TradeLine = os.date("%c", os.time(trade.datetime))..";"..
trade.class_code..";"..
trade.sec_code..";"..
trade.trade_num..";"..
trade.order_num..";"..
Op..";"..
trade.price..";"..
trade.qty.."\n";
-- Записывает строку в файл
CSV:write(TradeLine);
-- Сохраняет изменения в файле
CSV:flush();
end
end
function remove_line_from_csv(filename, line_to_remove)
local input_file = io.open(filename, "r")
if not input_file then
print("Ошибка открытия файла для чтения")
return false
end
local temp_filename = filename .. ".tmp"
local output_file = io.open(temp_filename, "w")
if not output_file then
print("Ошибка открытия временного файла для записи")
input_file:close()
return false
end
local line_number = 1
for line in input_file:lines() do
if line_number ~= line_to_remove then
output_file:write(line .. "\n")
end
line_number = line_number + 1
end
input_file:close()
output_file:close()
-- Удаляем старый файл и переименовываем временный
os.remove(filename)
os.rename(temp_filename, filename)
message("deleted")
end