-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
17 changed files
with
2,704 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
|
||
#### git clone https://github.com/WISEPLAT/QuikPy | ||
#### git clone https://github.com/WISEPLAT/BackTraderQuik | ||
|
||
1) для настройки интеграции с Quik (отсюда можно взять последнюю версию | ||
https://github.com/finsight/QUIKSharp/): | ||
2) в Quik -> Сервисы -> Lua скрипты -> нажимаем кнопку добавить и выбираем | ||
файл QuikSharp.lua из папки "lua" | ||
3) после добавления файла убеждаемся что он выбран, и нажимаем !!! | ||
на стрелку около кнопки Запустить, | ||
4) выбираем пункт "Запустить в Lua 5.3.5", после запуска в строке файла | ||
в поле "Память, КВ" начнут бежать цифры, | ||
5) и теперь нажимаем кнопку "Закрыть" - интеграция сделана | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,143 @@ | ||
--~ Copyright (c) 2014-2020 QUIKSharp Authors https://github.com/finsight/QUIKSharp/blob/master/AUTHORS.md. All rights reserved. | ||
--~ Licensed under the Apache License, Version 2.0. See LICENSE.txt in the project root for license information. | ||
|
||
-- is running from Quik | ||
function is_quik() | ||
if getScriptPath then return true else return false end | ||
end | ||
|
||
quikVersion = nil | ||
|
||
script_path = "." | ||
|
||
if is_quik() then | ||
script_path = getScriptPath() | ||
|
||
quikVersion = getInfoParam("VERSION") | ||
|
||
if quikVersion ~= nil then | ||
local t={} | ||
for str in string.gmatch(quikVersion, "([^%.]+)") do | ||
table.insert(t, str) | ||
end | ||
quikVersion = tonumber(t[1]) * 100 + tonumber(t[2]) | ||
end | ||
|
||
if quikVersion == nil then | ||
message("QUIK# cannot detect QUIK version", 3) | ||
return | ||
else | ||
libPath = "\\clibs" | ||
end | ||
|
||
-- MD dynamic, requires MSVCRT | ||
-- MT static, MSVCRT is linked statically with luasocket | ||
-- package.cpath contains info.exe working directory, which has MSVCRT, so MT should not be needed in theory, | ||
-- but in one issue someone said it doesn't work on machines that do not have Visual Studio. | ||
local linkage = "MD" | ||
|
||
--if quikVersion >= 811 then | ||
-- libPath = libPath .. "64\\54_MD\\" | ||
--elseif quikVersion >= 805 then | ||
if quikVersion >= 805 then | ||
libPath = libPath .. "64\\53_"..linkage.."\\" | ||
elseif quikVersion >= 800 then | ||
libPath = libPath .. "64\\5.1_"..linkage.."\\" | ||
else | ||
libPath = "\\clibs\\5.1_"..linkage.."\\" | ||
end | ||
end | ||
package.path = package.path .. ";" .. script_path .. "\\?.lua;" .. script_path .. "\\?.luac"..";"..".\\?.lua;"..".\\?.luac" | ||
package.cpath = package.cpath .. ";" .. script_path .. libPath .. '?.dll'..";".. '.' .. libPath .. '?.dll' | ||
|
||
local util = require("qsutils") | ||
local qf = require("qsfunctions") | ||
require("qscallbacks") | ||
|
||
log("Detected Quik version: ".. quikVersion .." and using cpath: "..package.cpath , 0) | ||
|
||
local is_started = true | ||
|
||
-- we need two ports since callbacks and responses conflict and write to the same socket at the same time | ||
-- I do not know how to make locking in Lua, it is just simpler to have two independent connections | ||
-- To connect to a remote terminal - replace '127.0.0.1' with the terminal ip-address | ||
-- All this values could be replaced with values from config.json | ||
local response_host = '127.0.0.1' | ||
local response_port = 34130 | ||
local callback_host = '127.0.0.1' | ||
local callback_port = response_port + 1 | ||
|
||
function do_main() | ||
log("Entered main function", 0) | ||
while is_started do | ||
-- if not connected, connect | ||
util.connect(response_host, response_port, callback_host, callback_port) | ||
-- when connected, process queue | ||
-- receive message, | ||
local requestMsg = receiveRequest() | ||
if requestMsg then | ||
-- if ok, process message | ||
-- dispatch_and_process never throws, it returns lua errors wrapped as a message | ||
local responseMsg, err = qf.dispatch_and_process(requestMsg) | ||
if responseMsg then | ||
-- send message | ||
local res = sendResponse(responseMsg) | ||
else | ||
log("Could not dispatch and process request: " .. err, 3) | ||
end | ||
else | ||
delay(1) | ||
end | ||
end | ||
end | ||
|
||
function main() | ||
setup("QuikSharp") | ||
run() | ||
end | ||
|
||
--- catch errors | ||
function run() | ||
local status, err = pcall(do_main) | ||
if status then | ||
log("finished") | ||
else | ||
log(err, 3) | ||
end | ||
end | ||
|
||
function setup(script_name) | ||
if not script_name then | ||
log("File name of this script is unknown. Please, set it explicity instead of scriptFilename() call inside your custom file", 3) | ||
return false | ||
end | ||
|
||
local list = paramsFromConfig(script_name) | ||
if list then | ||
response_host = list[1] | ||
response_port = list[2] | ||
callback_host = list[3] | ||
callback_port = list[4] | ||
printRunningMessage(script_name) | ||
elseif script_name == "QuikSharp" then | ||
-- use default values for this file in case no custom config found for it | ||
printRunningMessage(script_name) | ||
else -- do nothing when config is not found | ||
log("File config.json is not found or contains no entries for this script name: " .. script_name, 3) | ||
return false | ||
end | ||
|
||
return true | ||
end | ||
|
||
function printRunningMessage(script_name) | ||
log("Running from ".. script_name .. ", params: response " .. response_host .. ":" .. response_port ..", callback ".. " ".. callback_host ..":".. callback_port) | ||
end | ||
|
||
if not is_quik() then | ||
log("Hello, QUIK#! Running outside Quik.") | ||
setup("QuikSharp") | ||
do_main() | ||
logfile:close() | ||
end | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
--~ Copyright (c) 2014-2020 QUIKSharp Authors https://github.com/finsight/QUIKSharp/blob/master/AUTHORS.md. All rights reserved. | ||
--~ Licensed under the Apache License, Version 2.0. See LICENSE.txt in the project root for license information. | ||
|
||
script_path = getScriptPath() | ||
package.path = package.path .. ";" .. script_path .. "\\?.lua;" .. script_path .. "\\?.luac"..";"..".\\?.lua;"..".\\?.luac" | ||
require("QuikSharp") | ||
|
||
-- Do not edit this file. Just copy it and save with a different name. Then write required params for it inside config.json file | ||
-- Не редактируйте этой файл. Просто скопируйте и сохраните под другим именем. После этого укажите настройки для него в файле config.json | ||
|
||
function main() | ||
if setup(scriptFilename()) then | ||
run() | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
Использование Lua скриптов | ||
========== | ||
Lua скрипты из состава библиотеки позволяют работать с несколькими терминалами Quik одновременно. | ||
|
||
Как подключиться к двум терминалам сразу | ||
---------------------------------------- | ||
|
||
Достаточно сделать ряд простых действий: | ||
1. Найти в файле `config.json` секцию `servers`, там будет название опции `scriptName` со значением `Quik_2`. В данном случае `Quik_2` является названием файла в папке lua (расширение `.lua` в `config.json` указывать нельзя). | ||
2. Изменить опции согласно вашим предпочтениям. По умолчанию, дополнительный сокет сервер будет запущен на localhost'e (т.е. опции `responseHostname` и `callbackHostname` имеют значение `127.0.0.1`), а порты (опции `responsePort` и `callbackPort`) равны `34132` для сервера запросов-ответов и `34133` для сервера коллбэков (данные, которые хочет отправить Квик). Порты не должны конфликтовать с уже указанными портами в файле `config.json` | ||
3. Добавить `Quik_2.lua` в Quik и запустить. При этом необязательно запускать `QuikSharp.lua`, если он вами не используется. Если используется и для него указаны другие порты, то, безусловно, можно запускать оба. | ||
|
||
Все! | ||
|
||
Вопросы и ответы | ||
---------------- | ||
|
||
- Как добавить еще сервера? | ||
|
||
Скопируйте файл `Quik_2.lua` и сохраните его в той же папке под другим именем, например, `MyBroker.lua`. В файле `config.json` в секции `servers` скопируйте текст внутри фигурных скобок `{"scriptName"..."responseHostname"..."responsePort"..."callbackHostname"..."callbackPort"...}`, поставьте запятую после `}`, вставьте скопированный текст и измените в нем данные. Как минимум, нужно указать в `scriptName` название файла скрипта (в примере это `MyBroker`), а в опциях портов указать любые свободные номера портов. Такую процедуру можно делать столько раз, сколько серверов вам нужно. Не забудьте, что `responsePort` и `callbackPort` не могут быть одинаковыми и повторяться в файле. | ||
|
||
- Как обновляться на новые версии библиотеки и скриптов в частности? | ||
|
||
В новых версиях будет меняться код скриптов и код `config.json`. Но если вы вносили изменения в `config.json`, то сохраните в другом месте файл с вашими изменениями. После этого замените все старые файлы новыми. Обратите внимание, что, возможно, в одном из обновлений содержимое `Quik_2.lua` изменится и все созданные вами лично копии этого файла потребуется пересоздать на основе обновленного файла. Продолжаем. Отредактируйте файл `config.json` в соответствии с настройками из старого файла (если не меняли ничего, делать ничего не надо). Процесс обновления завершен. | ||
|
||
- Как сделать так, чтобы можно было подключаться к сокету из локальной сети WiFi с другого устройства? | ||
|
||
Нужно указать в `responseHostname` и `callbackHostname` значение `0.0.0.0`. Лучше так не делать и вот, почему. Когда компьютер подключен к роутеру, то разрешение подключаться к нему извне (а именно это делает `0.0.0.0`) открывает доступ к нему всему миру при допущении, что роутер недостаточно хорошо защищен и настроен. А так как при подключении к сокетам нет ни пароля, ни шифрования, открытый доступ всему миру открывает ваш Квик всем. Т.е. если вы все же хотите подключаться из локальной сети, позаботьтесь о безопасности и верных настройках роутера. | ||
|
||
- Можно ли переименовать `Quik_2.lua`? | ||
|
||
Да, только укажите новое имя в `scriptName` файла `config.json`. | ||
|
||
|
||
- Можно ли переименовать `QuikSharp.lua`? | ||
|
||
Нет. Этот файл обязательно должен сохранить свое имя, потому что все остальные скрипты используют часть его кода. |
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
{ | ||
"servers": [ | ||
{ | ||
"scriptName": "QuikSharp", | ||
"responseHostname": "127.0.0.1", | ||
"responsePort": 34130, | ||
"callbackHostname": "127.0.0.1", | ||
"callbackPort": 34131 | ||
}, | ||
{ | ||
"scriptName": "Quik_2", | ||
"responseHostname": "127.0.0.1", | ||
"responsePort": 34132, | ||
"callbackHostname": "127.0.0.1", | ||
"callbackPort": 34133 | ||
} | ||
] | ||
} |
Oops, something went wrong.