TroExol / TI.auto

// ==UserScript==
// @name         TI.auto
// @namespace    https://vk.com/TroExol
// @version      1.0.0.1
// @description  Автоматическая продажа и покупка
// @author       TroExol
// @copyright    2018, TroExol (https://vk.com/TroExol)
// @match        https://tradeit.gg/inventory
// @license      MIT
// @grant        none
// ==/UserScript==

// ==OpenUserJS==
// @author TroExol
// ==/OpenUserJS==

function time_unix(){
    return parseInt(new Date().getTime()/10)
}

if (localStorage.getItem('tr_id_user') === null) {
    localStorage.setItem('tr_id_user', time_unix());
}

$('head').append('<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">');
function loadScript(url) {
    s = document.createElement('script');
    s.src = url;
    (document.head || document.documentElement).appendChild(s)
    console.log('Загружено '+url);
}

loadScript('https://progamestak.ru/src/libs/js/jquery.min.js');

$(document).ready(function() {

    $('head').append('<style>.config {position: fixed; z-index: 99999; width: 266px; border: 1px solid #fff; padding: 5px; background-color: rgba(31, 33, 38, 0.7); color: rgba(255,255,255,1); font-size: 13px;} ul,li {list-style-type: none;} a, a:active, a:focus, button, button:active, button:focus, input, input:active, input:focus{outline: none; text-decoration: none; border: none;} .logs h2{font-size: 1rem;} .logs hr {margin-block-start: 2px;margin: 4px 0;background: #fff;} .logs {position: fixed; z-index: 99999; width: 170px; border: 1px solid #fff; padding: 5px; background-color: rgba(31, 33, 38, 0.7); color: rgba(255,255,255,1); font-size: 13px;} .logs ul {padding: 3px; color: aquamarine; word-wrap: break-word; height: 203px; overflow: auto;}</style>');

    // От какого процента прибыли
    var from_percent_profit = 0,
        // От скольки $ закупать (0 - выключено)
        from_price_buy = 0,
        // От скольки $ желаемой продажи предмета после трейд бана (0 - выключено)
        from_price_sell = 0,
        // До скольки $ закупать (0 - выключено)
        to_price_buy = 0,
        // До скольки $ желаемой продажи предмета после трейд бана (0 - выключено)
        to_price_sell = 0,
        // Перезагрузка страницы каждые ? мин
        time_to_reload = 7,
        // Задержка трейд бана
        ban_days_config = 4,
        // Автопокупка
        auto_buy = 'false',
        // Автопродажа
        auto_sell = 'false';

    function config_edit() {
        $.ajax({
            url: 'http://progamestak.ru/tradeit/logs.php/',
            type: 'POST',
            dataType: 'html',
            data: {
                query_type: 'config_edit',
                id_user: localStorage.getItem('tr_id_user'),
                from_percent_profit: $('#from_percent_profit').val(),
                from_price_buy: $('#from_price_buy').val(),
                from_price_sell: $('#from_price_sell').val(),
                to_price_buy: $('#to_price_buy').val(),
                to_price_sell: $('#to_price_sell').val(),
                time_to_reload: $('#time_to_reload').val(),
                ban_days_config: $('#ban_days_config').val(),
                auto_sell: $('#auto_sell').is(':checked'),
                auto_buy: $('#auto_buy').is(':checked')
            }
        })
            .done(function() {
            console.log('Сохранено');
        })
            .fail(function() {
            console.log("Ошибка изменения настроек");
        })
    }
    setTimeout(function() {
        $('#config_edit').click(function() {config_edit();});
    },1000);

    $.ajax({
        url: 'http://progamestak.ru/tradeit/logs.php/',
        type: 'POST',
        dataType: 'json',
        data: {
            query_type: 'take_config',
            id_user: localStorage.getItem('tr_id_user')
        },
        success: function(res){
            if (res.success != 'error') {

                from_percent_profit = res.from_percent_profit;
                from_price_buy = res.from_price_buy;
                from_price_sell = res.from_price_sell;
                to_price_buy = res.to_price_buy;
                to_price_sell = res.to_price_sell;
                time_to_reload = res.time_to_reload;
                ban_days_config = res.ban_days;
                auto_sell = res.auto_sell;
                auto_buy = res.auto_buy;

                if (auto_sell == 'true') auto_sell = 'checked';
                if (auto_buy == 'true')	auto_buy = 'checked';
            } else {

                from_percent_profit = 0;
                from_price_buy = 0;
                from_price_sell = 0;
                to_price_buy = 0;
                to_price_sell = 0;
                time_to_reload = 7;
                ban_days_config = 4;
                auto_sell = 'false';
                auto_buy = 'false';
            }
            // Блок настройки скрипта
            $('body').append('<div id="config" class="config" style="bottom: 5px; right: 5px;"><button id="config_edit" style="position: absolute; top:2px; right: 2px; cursor: pointer;">Сохранить</button><h2>Настройки</h2><label>Процент прибыли от<input id="from_percent_profit" type="number" value="'+from_percent_profit+'"></label><label>От скольки $ закупать (0-выкл)<input id="from_price_buy" type="number" value="'+from_price_buy+'"></label><label>От скольки $ желаемой продажи (0-выкл)<input id="from_price_sell" type="number" value="'+from_price_sell+'"></label><label>До скольки $ закупать (0-выкл)<input id="to_price_buy" type="number" value="'+to_price_buy+'"></label><label>До скольки $ желаемой продажи (0-выкл)<input id="to_price_sell" type="number" value="'+to_price_sell+'"></label><label>Перезагрузка страницы каждые (мин)<input id="time_to_reload" type="number" value="'+time_to_reload+'"></label><label>Макс трейд бан (дни)<input id="ban_days_config" type="number" value="'+ban_days_config+'"></label><label>Вкл автопокупку<input id="auto_buy" type="checkbox" '+auto_buy+'></label><label>Вкл автопродажу<input id="auto_sell" type="checkbox" '+auto_sell+'></label></div>');

        },
        error: function(res){
            console.log("Ошибка получения настроек");
        }
    });

    from_percent_profit = $('#from_percent_profit').val(),
        from_price_buy = $('#from_price_buy').val(),
        from_price_sell = $('#from_price_sell').val(),
        to_price_buy = $('#to_price_buy').val(),
        to_price_sell = $('#to_price_sell').val(),
        time_to_reload = $('#time_to_reload').val(),
        ban_days_config = $('#ban_days_config').val(),
        auto_sell = $('#auto_sell').is(':checked'),
        auto_buy = $('#auto_buy').is(':checked');

    setTimeout(function() {
        // Форматирование даты
        function formDate(str) {
            var date = new Date();

            if (str.toLowerCase() == 'year') {
                res = date.getFullYear().toString().substr(-2);
            }

            if (str.toLowerCase() == 'month') {
                res = date.getMonth() + 1;
                if (res < 10) {
                    res = '0' + res;
                }
            }

            else if (str.toLowerCase() == 'day') {
                var res = date.getDate();
                if (res < 10) {
                    res = '0' + res;
                }
            }

            else if (str.toLowerCase() == 'hours') {
                var res = date.getHours();
                if (res < 10) {
                    res = '0' + res;
                }
            }

            else if (str.toLowerCase() == 'minutes') {
                var res = date.getMinutes();
                if (res < 10) {
                    res = '0' + res;
                }
            }

            return res;
        };

        // Создание даты
        function genDate() {
            var year = formDate('year'),
                month = formDate('month'),
                day = formDate('day'),
                hours = formDate('hours'),
                minutes = formDate('minutes');
            return day+'.'+month+'.'+year+' '+hours+':'+minutes;
        }
        // Блок логов продажи
        $('body').append('<div id="logs_sell" class="logs" style="top: 5px; left: 5px;"><h2>Продажи</h2><ul></ul></div>');
        // Блок логов покупки
        $('body').append('<div id="logs_buy" class="logs" style="top: 270px; left: 5px;"><h2>Покупки</h2><ul></ul></div>');

        // Заполнение логов
        $.ajax({
            url: 'https://progamestak.ru/tradeit/logs.php/',
            type: 'POST',
            dataType: 'json',
            data: {
                query_type: 'take_sells',
                id_user: localStorage.getItem('tr_id_user')
            },
            success: function(res){
                if (res.length != 0) {
                    for (i=0; i < res.length; i++) {
                        $('#logs_sell > ul').prepend('<li>'+res[i].name+'<br>Покупка за '+res[i].price_buy+'$<br>Продажа за '+res[i].price_sell+'$<br>Процент выгоды: '+res[i].percent+'<br>Время продажи: '+res[i].date+'</li><hr>');
                    }
                }
            },
            error: function(res){
                console.log("Ошибка получения логов");
            }
        });

        $.ajax({
            url: 'https://progamestak.ru/tradeit/logs.php/',
            type: 'POST',
            dataType: 'json',
            data: {
                query_type: 'take_buy',
                id_user: localStorage.getItem('tr_id_user')
            },
            success: function(res){
                if (res.length != 0) {
                    for (i=0; i < res.length; i++) {
                        $('#logs_buy > ul').prepend('<li>'+res[i].name+'<br>Покупка за '+res[i].price_buy+'$<br>Продажа за '+res[i].price_sell+'$<br>Процент выгоды: '+res[i].percent+'%<br>Трейд бан: '+res[i].tradeban+' день/дня <br>Время покупки: '+res[i].date+'</li><hr>');
                    }
                }
            },
            error: function(res){
                console.log("Ошибка получения логов");
            }
        });
        from_percent_profit = $('#from_percent_profit').val(),
            from_price_buy = $('#from_price_buy').val(),
            from_price_sell = $('#from_price_sell').val(),
            to_price_buy = $('#to_price_buy').val(),
            to_price_sell = $('#to_price_sell').val(),
            time_to_reload = $('#time_to_reload').val(),
            ban_days_config = $('#ban_days_config').val(),
            auto_sell = $('#auto_sell').is(':checked'),
            auto_buy = $('#auto_buy').is(':checked');
        if (auto_sell == true) {
            setTimeout(function() {
                if ($('#playerinv-content > tr') && $('#playerinv-content .btn-info').is('[onclick]')) {
                    $('#playerinv-content > tr').each(function(i, e) {

                        // Цена покупки
                        var price_buy = parseFloat($(this).find('td:nth-child(2)').text().replace(/[^,.0-9]/gim, "")).toFixed(2),
                            // Название шмотки
                            name = $(this).find('td:nth-child(1)').text(),
                            date = genDate(),
                            // Кнопка продажи
                            btn_sell = $(this).find('td:nth-child(4)').children('.btn-info'),
                            // Цена продажи
                            price_sell = parseFloat(btn_sell.text().replace(/[^,.0-9]/gim, "")).toFixed(2),
                            // Процент выгоды
                            percent = Math.floor((price_sell-price_buy)/(price_buy/100));

                        // Проверка на выгодность продажи и доступность кнопки
                        if (percent >= from_percent_profit && btn_sell.is('[onclick]')) {

                            // Сохрание лога
                            $.ajax({
                                url: 'https://progamestak.ru/tradeit/logs.php/',
                                type: 'POST',
                                dataType: 'html',
                                data: {
                                    query_type: 'create_logssell',
                                    id_user: localStorage.getItem('tr_id_user'),
                                    name: name,
                                    price_buy: price_buy,
                                    price_sell: price_sell,
                                    percent: percent,
                                    date: date
                                },
                            })
                                .done(function() {
                                $('#logs_sell > ul').prepend('<li>'+name+'<br>Покупка за '+price_buy+'$<br>Продажа за '+price_sell+'$<br>Процент выгоды: '+percent+'%<br>Дата продажи: '+date+'</li><hr>');
                            })
                                .fail(function() {
                                console.log("Ошибка записи логов");
                            })

                            // Продажа
                            btn_sell.click();

                        }
                    });
                    // end each
                }
            }, 2000);
        }
        if (auto_buy == true) {

            // Получение страницы инвентаря
            var inv_page = $.ajax({
                url: "https://tradeit.gg/inventory",
                async: false
            }).responseText;

            // Получение баланса аккаунта
            if (inv_page) {
                var bal = inv_page.match(/id="balance">.\s\d+\.\d+/);
                bal = bal[0].replace(/id="balance">.\s/, '');
            }
            console.log('%cБаланс аккаунта: '+bal+'$', 'color: green');

            // Получение инвентарей ботов
            var inv = $.ajax({
                url: "https://inventory.tradeit.gg/sinv",
                async: false
            }).responseText;

            if (inv) {
                inv = JSON.parse(inv); // Преобразование в JSON объект

                // Получение инвентарей ботов в CS:GO
                var inv_cs = [];

                for (var i = 0; i < inv.length; i++) {
                    inv_cs[i] = inv[i][730].items;
                }

                // Поиск выгодных предметов
                var max_profit_item = [],
                    max_profit_item_name = [],
                    ban_days = [],
                    max_profit_percent = [],
                    bot = [];

                ban_days[0] = 100;
                if (to_price_sell == 0) to_price_sell = 1000000;
                if (to_price_buy == 0) to_price_buy = 1000000;

                for (var i = 0; i < inv_cs.length; i++) {
                    $.each(inv_cs[i], function(k, v) {
                        // Цена со скидкой
                        var price_buy = v.d[0].p,
                            // Цена без скидки
                            price_sell = v.p,
                            // Качество предмета
                            quality = v.e;

                        // Поиск выгодных предметов
                        if ( price_buy && price_sell >= from_price_sell*100 && price_sell <= to_price_sell*100 && price_buy <= to_price_buy*100 && price_buy >= from_price_buy*100 && Math.floor((price_sell-price_buy)/(price_buy/100)) >= from_percent_profit && (max_profit_percent[0] < Math.floor((price_sell-price_buy)/(price_buy/100)) || max_profit_percent.length == 0) ) {

                            // Наличие трейд бана предмета
                            if (v.d[0].r) {
                                ban_days[2] = v.d[0].r-Math.floor(Date.now()/3600000);
                                ban_days[2] = Math.ceil(ban_days[i]/24);

                                if (ban_days[2] <= ban_days_config) {

                                    ban_days[1] = ban_days[0];
                                    ban_days[0] = ban_days[2];

                                    max_profit_item[1] = max_profit_item[0];
                                    max_profit_item[0] = v;

                                    max_profit_item_name[1] = max_profit_item_name[0];
                                    max_profit_item_name[0] = k;

                                    max_profit_percent[1] = max_profit_percent[0];
                                    max_profit_percent[0] = Math.floor((price_sell-price_buy)/(price_buy/100));

                                    bot[1] = bot[0];
                                    bot[0] = i+1;
                                }
                            }	else if (!v.d[0].r) {
                                ban_days[1] = ban_days[0];
                                ban_days[0] = 'Без бана';

                                max_profit_item[1] = max_profit_item[0];
                                max_profit_item[0] = v;

                                max_profit_item_name[1] = max_profit_item_name[0];
                                max_profit_item_name[0] = k;

                                max_profit_percent[1] = max_profit_percent[0];
                                max_profit_percent[0] = Math.floor((price_sell-price_buy)/(price_buy/100));

                                bot[1] = bot[0];
                                bot[0] = i+1;
                            }
                        }
                    });
                }

                // Самый профитный предмет
                var price_buy = [],
                    price_sell = [],
                    item_index = [],
                    dif_bal_buy = [],
                    trade_success = false,
                    quality = [];
                if (max_profit_item_name.length != 0) {

                    for (i=0; i<max_profit_item.length, max_profit_item[i]; i++) {

                        // Цена со скидкой
                        price_buy[i] = max_profit_item[i].d[0].p,
                            // Цена без скидки
                            price_sell[i] = max_profit_item[i].p,
                            // Индекс предмета
                            item_index[i] = max_profit_item[i].d[0].i,
                            // Разница между балансом и ценой покупки
                            dif_bal_buy[i] = (price_buy[i]/100-bal).toFixed(2),
                            // Название предмета
                            max_profit_item_name[i] = max_profit_item_name[i].slice(11),
                            // Качество предмета
                            quality[i] = max_profit_item[i].e;

                        if (typeof ban_days[i] == 'number') ban_days[i] = ban_days[i]+' день/дня/дней';

                        if (dif_bal_buy[i] < 0) {

                            if (quality[i]) console.log('%c'+max_profit_item_name[i]+' '+quality[i]+' \n%cЦена со скидкой: '+price_buy[i]/100+'$ \nЦена без скидки: '+price_sell[i]/100+'$ \nВыгода: '+max_profit_percent[i]+'% \nВремя трейд бана: '+ban_days[i]+' \nБот: '+bot[i], 'color: #42827D;', 'color: #000;');
                            else console.log('%c'+max_profit_item_name[i]+' \n%cЦена со скидкой: '+price_buy[i]/100+'$ \nЦена без скидки: '+price_sell[i]/100+'$ \nВыгода: '+max_profit_percent[i]+'% \nВремя трейд бана: '+ban_days[i]+' \nБот: '+bot[i], 'color: #42827D;', 'color: #000;');

                            console.log(max_profit_item[i]);

                        }	else {

                            if (quality[i]) console.log('%c'+max_profit_item_name[i]+' '+quality[i]+' \n%cЦена со скидкой: '+price_buy[i]/100+'$ \nЦена без скидки: '+price_sell[i]/100+'$ \nВыгода: '+max_profit_percent[i]+'% \nВремя трейд бана: '+ban_days[i]+' \nБот: '+bot[i], 'color: #42827D;', 'color: #000;');
                            else console.log('%c'+max_profit_item_name[i]+' \n%cЦена со скидкой: '+price_buy[i]/100+'$ \nЦена без скидки: '+price_sell[i]/100+'$ \nВыгода: '+max_profit_percent[i]+'% \nВремя трейд бана: '+ban_days[i]+' \nБот: '+bot[i], 'color: #42827D;', 'color: #000;');

                            if (quality[i]) console.log('%cНе хватает баланса: '+dif_bal_buy[i]+'$ для покупки '+max_profit_item_name[i]+' '+quality[i], 'color: red;');
                            else console.log('%cНе хватает баланса: '+dif_bal_buy[i]+'$ для покупки '+max_profit_item_name[i], 'color: red;');

                            console.log(max_profit_item[i]);
                        }
                    }
                }	else console.log('%cВыгодные предметы отсутствуют', 'color: rgba(231, 54, 57, 1);');
            }

            function randomInteger(min, max) {
                var rand = min - 0.5 + Math.random() * (max - min + 1)
                rand = Math.round(rand);
                return rand;
            }

            if (max_profit_item[0]) {
                var data_post = [],
                    av_item = true;

                if (dif_bal_buy[0] < 0) {
                    bot = bot[0]-1;
                    index = item_index[0]+'_'+bot;
                    data_post = {'sselected[]': index, 'value': price_buy[0]};
                }
                else if (dif_bal_buy[1] < 0) {
                    bot = bot[1]-1;
                    index = item_index[1]+'_'+bot;
                    data_post = {'sselected[]': index, 'value': price_buy[1]};
                }
                else av_item = false;

                if (av_item == true) {

                    $.ajax({
                        url: "https://tradeit.gg/reserve",
                        type: 'POST',
                        data: data_post,
                        success: function(data) {
                            console.log(data);
                            data = JSON.parse(data);

                            if (data.succes == false && max_profit_item[1] && dif_bal_buy[1] < 0 && data_post['sselected[]'] != item_index[1]) {

                                setTimeout(function() {
                                    $.ajax({
                                        url: "https://tradeit.gg/reserve",
                                        type: 'POST',
                                        data: {
                                            'sselected[]': item_index[1]+'_'+bot[1]-1,
                                            value: price_buy[1]
                                        },
                                        success: function(data) {
                                            console.log(data);
                                            date = JSON.parse(data);
                                            if (date.succes == true) {
                                                var data_logs = [],
                                                    name = '',
                                                    date = genDate();
                                                if (quality[i]) name = max_profit_item_name[0]+' '+quality[0];
                                                else name = max_profit_item_name[0];

                                                $.ajax({
                                                    url: 'https://progamestak.ru/tradeit/logs.php/',
                                                    type: 'POST',
                                                    dataType: 'html',
                                                    data: {
                                                        query_type: 'create_logsbuy',
                                                        id_user: localStorage.getItem('tr_id_user'),
                                                        name: name,
                                                        price_buy: price_buy[1]/100,
                                                        price_sell: price_sell[1]/100,
                                                        percent: max_profit_percent[1],
                                                        tradeban: ban_days[1],
                                                        date: date
                                                    },
                                                })
                                                    .done(function() {
                                                    $('#logs_buy > ul').prepend('<li>'+name+'<br>Покупка за '+price_buy[1]/100+'$<br>Продажа за '+price_sell[1]/100+'$<br>Процент выгоды: '+max_profit_percent[1]+'%<br>Трейд бан: '+ban_days[1]+' день/дня <br>Дата продажи: '+date+'</li><hr>');
                                                })
                                                    .fail(function() {
                                                    console.log("Ошибка записи логов");
                                                })
                                            }
                                        },
                                        error: function (error) {
                                            console.log('error; '+error);
                                        }
                                    });
                                }, randomInteger(10000, 12000));
                            } else {
                                var data_logs = [],
                                    name = '',
                                    date = genDate();
                                if (quality[i]) name = max_profit_item_name[0]+' '+quality[0];
                                else name = max_profit_item_name[0];

                                $.ajax({
                                    url: 'https://progamestak.ru/tradeit/logs.php/',
                                    type: 'POST',
                                    dataType: 'html',
                                    data: {
                                        query_type: 'create_logsbuy',
                                        id_user: localStorage.getItem('tr_id_user'),
                                        name: name,
                                        price_buy: price_buy[0]/100,
                                        price_sell: price_sell[0]/100,
                                        percent: max_profit_percent[0],
                                        tradeban: ban_days[0],
                                        date: date
                                    },
                                })
                                    .done(function() {
                                    $('#logs_buy > ul').prepend('<li>'+name+'<br>Покупка за '+price_buy[0]/100+'$<br>Продажа за '+price_sell[0]/100+'$<br>Процент выгоды: '+max_profit_percent[0]+'%<br>Время трейд бана: '+ban_days[0]+' день/дня <br>Дата продажи: '+date+'</li><hr>');
                                })
                                    .fail(function() {
                                    console.log("Ошибка записи логов");
                                })
                            }
                            // end else
                        },
                        error: function (error) {
                            console.log('error; '+error);
                        }
                    });
                    // end ajax
                }
            }
        }
    }, 3000);
    setTimeout(function() {
        setTimeout(function() {
            location.reload();
        }, time_to_reload*80000);
    }, 4000);
});