Package psconsole

Source Code of psconsole.MainForm

/*
* Neiro Technology 2011-2014
*/
package psconsole;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.Vector;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.DefaultListSelectionModel;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
import javax.swing.text.MaskFormatter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import psconsole.UserItemRenderer.UserItemValue;
import psconsole.SymbolList.Symbol;
import psconsole.OrderList.OrderItem;
import psconsole.MainForm.OrdersTableModel.OrderData;
import psconsole.TaskManager.TaskOrder;
import psconsole.TaskManager.Task;
import psconsole.TaskManager.ReciveOrderCheck;
import textsockets.PSPackage;

/**
* Главная форма консоли
* @author deathNC
*/
public class MainForm extends javax.swing.JFrame {
   
    /**
     * Creates new form MainForm
     */
    public MainForm() {
        //super();
        initComponents();
        initImages();
       
        SettingsXMLFile settBuff = null;
        try {
            settBuff = new SettingsXMLFile(getScriptDirectory() + "/Settings.xml", "psconsole");
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
        settings = settBuff;
       
        sdfCurrentTime = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        sdfCurrentTime.setTimeZone(TimeZone.getTimeZone("Etc/GMT+0"));
        random = new Random();
        timeCurrent = 0;
        timeCurrentCalendar = new GregorianCalendar(TimeZone.getTimeZone("Etc/GMT+0"));
        //setCurrentTime(System.currentTimeMillis());
       
        panePrev = null;
        paneCurrent = "pnlTrading";
       
        convUSDRUR = 32.7315;
        convEURRUR = 41.0;
       
        //<editor-fold desc=" JTables ">
       
        // -- REAL-TIME ORDERS TABLE -------------------------------------------
        ordersModel = new OrdersTableModel();
        lstOrders.setModel(ordersModel);
        ordersRenderer = new OrdersTableCellRenderer();
        TableColumnModel tcm = lstOrders.getColumnModel();
        for (int i = 0; i < tcm.getColumnCount(); ++i)
            tcm.getColumn(i).setCellRenderer(ordersRenderer);
        lstOrders.getTableHeader().setDefaultRenderer(new OrderTableHeaderRenderer(lstOrders));
        lstOrders.setRowHeight(18);
        spOrders.getViewport().setBackground(Color.white);
       
        // -- TASK ORDERS TABLE ------------------------------------------------
        taskOTM = new TaskOrdersTableModel(
            new Object [][] {},
            new String [] {"Symbol", "Type", "Size", "Deviation", "Stoploss",
                "Takeprofit", "Trailing", "Time"}
        );
        lstNewOrders.setModel(taskOTM);
        TableCellRenderer cellRenderer = new TaskOrdersTableCellRenderer();
        for (int i = 0; i < lstNewOrders.getColumnModel().getColumnCount(); ++i)
            lstNewOrders.getColumnModel().getColumn(i).setCellRenderer(cellRenderer);
        tcm = lstNewOrders.getColumnModel();
        txtSymbolEditor = new JTextField();
        txtSymbolEditor.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                String s = txtSymbolEditor.getText();
                if (s.isEmpty() || !Character.isLetter(e.getKeyChar())) return;
                Symbol smb = symbolList.search(s);
                if (smb == null) return;
                txtSymbolEditor.setText(smb.symbol);
                txtSymbolEditor.setSelectionStart(s.length());
                txtSymbolEditor.setSelectionEnd(smb.symbol.length());
            }
        });
        txtSymbolEditor.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                txtSymbolEditor.selectAll();
            }
        });
        txtSymbolEditor.setBorder(new EmptyBorder(1, 2, 0, 0));
        tcm.getColumn(0).setCellEditor(new DefaultCellEditor(txtSymbolEditor));
       
        JComboBox<TaskOrder.Type> jcbOrderType = new JComboBox<>(TaskOrder.Type.values());
        tcm.getColumn(1).setCellEditor(new DefaultCellEditor(jcbOrderType));
        lstNewOrders.setRowHeight(18);
       
        // CheckBox (use breakeven)
        lstNewOrders.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                int[] selRows = lstNewOrders.getSelectedRows();
                int state = 0;
                // -- получение статуса и присвоение Enabled
                if (selRows.length > 0) {
                    if (!chkUseBreakeven.isEnabled()) chkUseBreakeven.setEnabled(true);
                    for (int i = 0; i < selRows.length; ++i) {
                        if (taskOTM.getOrder(selRows[i]).useBreakeven) state |= 1;
                        else state |= 2;
                    }
                }
                // -- выбор значков по state
                if (state == 3) {
                    chkUseBreakeven.setIcon(chbox_other);
                    chkUseBreakeven.setRolloverIcon(chbox_otherMoused);
                } else {
                    chkUseBreakeven.setIcon(chbox_icon);
                    chkUseBreakeven.setRolloverIcon(chbox_iconMoused);
                }
                // обновление чекбокса
                chkUseBreakeven.setSelected(state == 1);
                chkUseBreakeven.setEnabled(state != 0);
                chkUseBreakeven.updateUI();
            }
        });
       
        // Cell Editor (Default)
        JTextField jtf = new JTextField();
        final TableCellEditor tce = new DefaultCellEditor(jtf);
        jtf.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                ((JTextField)(e.getComponent())).selectAll();
            }
            @Override
            public void focusLost(FocusEvent e) {
                tce.cancelCellEditing();
            }
        });
        jtf.setBorder(new EmptyBorder(1, 2, 0, 0));
        for (int i = 2; i < tcm.getColumnCount(); ++i)
            tcm.getColumn(i).setCellEditor(tce);
       
        // -- TASK TABLE -------------------------------------------------------
        taskCellRenderer = new TaskTableCellRenderer();
        String[] columnNames = {"Задача", "ID", "Статус"};
        taskModel = new TaskTableModel(columnNames);
        lstTaskList.setModel(taskModel);
        tcm = lstTaskList.getColumnModel();
        for (int i = 0; i < tcm.getColumnCount(); ++i)
            tcm.getColumn(i).setCellRenderer(taskCellRenderer);
        tcm.getColumn(2).setMaxWidth(164);
        tcm.getColumn(2).setMinWidth(162);
        tcm.getColumn(2).setResizable(false);
        tcm.getColumn(1).setMaxWidth(128);
        tcm.getColumn(1).setMinWidth(128);
        tcm.getColumn(1).setResizable(false);
        lstTaskList.getTableHeader().setReorderingAllowed(false);
        //</editor-fold>
       
        //<editor-fold desc=" lists ">
        listModel = new DefaultListModel<>();
        lstUsers.setModel(listModel);
        listModelSmb = new DefaultListModel<>();
        lstSymbols.setModel(listModelSmb);
        symbolList = new SymbolList(listModelSmb);
       
        pnlRenderUsers = new UserItemRenderer();
        lstUsers.setCellRenderer(new DefaultListCellRenderer() {
            public Component getListCellRendererComponent(JList list,
                         Object value, int index, boolean isSelected,
                         boolean cellHasFocus) {
                UserItemValue val = (UserItemValue)value;
                if (val.accountID == -1) {
                    val.balance = 0.0;
                    val.profit = 0.0;
                    val.terminalCount = listModel.getSize() - 1;
                    for (int i = 0; i < listModel.getSize(); ++i) {
                        UserItemValue item = (UserItemValue)listModel.get(i);
                        if (item.accountID == -1) continue;
                        val.balance += item.balance;
                        val.profit += item.profit;
                    }
                }
                pnlRenderUsers.setItemSelected(isSelected);
                pnlRenderUsers.setValue(val, MainForm.this);
                pnlRenderUsers.setIconName(val.terminalConnected ? userActive3 : userActive1);
                return pnlRenderUsers;
            }
        });
        lstUsers.setFixedCellHeight(48);
        lstUsers.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                List<UserItemValue> items = getSelectedUsers();
                onUserSelected(items, paneCurrent);
               
            }
        });
        //DefaultListSelectionModel smodel = (DefaultListSelectionModel)lstUsers.getSelectionModel();
        //smodel.
       
        listModel.addElement(new UserItemValue(-1, "Все счета", 0, 0));
        //<editor-fold desc=" test list ">
        /*UserItemValue[] bf = new UserItemValue[6];
        double d = 0;
        bf[0] = new UserItemValue(18051, "Быков А.П.",      doGDev(6192.01, 10), d);
        bf[1] = new UserItemValue(18505, "Гаер А.В.",       doGDev(3256.16, 10), d);
        bf[2] = new UserItemValue(18343, "Теряев В.Л.",     doGDev(6500.1,  10), d);
        bf[3] = new UserItemValue(18065, "Михельсон А.К.",  doGDev(6900.9,  10), d);
        bf[4] = new UserItemValue(18050, "Артёмов К.П.",    doGDev(6352.0,  10), d);
        bf[5] = new UserItemValue(18249, "Фёдоров Д.В.",    doGDev(16598.27,10), d);
        for (int i = 0; i < bf.length; ++i) {
            bf[i].terminalConnected = random.nextBoolean();
            bf[i].profit = bf[i].balance / 15.0 * random.nextGaussian();
            listModel.addElement(bf[i]);
        }*/
        //</editor-fold>
        //</editor-fold>
       
        //<editor-fold desc=" labels highlighers ">
        lblHighligh = new LabelHighligher();
        lblCreateTask.addMouseListener(lblHighligh);
        lblAddOrder.addMouseListener(lblHighligh);
        lblDeleteOrder.addMouseListener(lblHighligh);
        lblClearOrders.addMouseListener(lblHighligh);
        lblGoSettings.addMouseListener(lblHighligh);
        lblAddSmb.addMouseListener(lblHighligh);
        lblRemoveAccount.addMouseListener(lblHighligh);
        lblGoTrading.addMouseListener(lblHighligh);
        lblGoNewOrder.addMouseListener(lblHighligh);
        lblDoModify.addMouseListener(lblHighligh);
        //</editor-fold>
       
        //<editor-fold desc=" JTextFields ">
       
        txtUserNameEditor.setBorder(new EmptyBorder(0,0,0,0));
        txtUserNameEditor.setBackground(getBackground());
        txtUserNameEditor.setSelectionColor(changeColor(getBackground(), 25));
        txtUserNameEditor.setSelectedTextColor(Color.black);
       
        //txtTaskDate.setPreferredSize(null);
       
        //</editor-fold>
       
        numsys = new NumeralSystems();
        tmManager = new TimeManager(System.currentTimeMillis(), this);
        taskManager = new TaskManager(this);
       
        // -- запуск сервера
        try {
            server = new ServerConsole(6611, this);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(0);
        }
       
        loadOptions();
    }
   
    private void loadOptions() {
        try {
            Document doc = settingsLoadXML();
            Element root = doc.getDocumentElement();

            Element item = searchNode(root, "/settings/general/");
            if (item != null) {
                Element el = searchNode(item, "/crazy");
                int i = Integer.parseInt(el.getAttribute("ind"));
                if (i == 1) btnGroupCrazy.setSelected(rbCrazyAlt.getModel(), true);
                else if (i == 2) btnGroupCrazy.setSelected(rbCrazyCtrl.getModel(), true);
                else btnGroupCrazy.setSelected(rbCrazyCtrl.getModel(), true);
            }

            item = searchNode(root, "/settings/symbols/");
            if (item != null) symbolList.importFromXML(item);
           
            // -- сохранение положения окна
            item = searchNode(root, "/settings/general/bounds");
            if (item != null) {
                int x = Integer.parseInt(item.getAttribute("left"));
                int y = Integer.parseInt(item.getAttribute("top"));
                int w = Integer.parseInt(item.getAttribute("width"));
                int h = Integer.parseInt(item.getAttribute("height"));
                setSize(w, h);
                setLocation(x, y);
            }
           
            // -- Время до отправки ордеров
            item = searchNode(root, "/settings/timeSecOffset");
            if (item != null) {
                int vl = Integer.parseInt(item.getAttribute("sec"));
                spnOrderSendSeconds.getModel().setValue(new Integer(vl));
            }
           
            item = searchNode(root, "/settings/maxTasks");
            if (item != null) {
                int vl = Integer.parseInt(item.getAttribute("value"));
                spnMaxTasks.getModel().setValue(new Integer(vl));
            }
           
            // -- курсы валют (в российских рублях)
            item = searchNode(root, "/settings/currencyValues");
            if (item != null) {
                String s = item.getAttribute("usd");
                if (s != null && !s.isEmpty()) {
                    convUSDRUR = Double.parseDouble(s);
                    txtUSDValue.setText(s);
                }
                s = item.getAttribute("eur");
                if (s != null && !s.isEmpty()) {
                    convEURRUR = Double.parseDouble(s);
                    txtEURValue.setText(s);
                }
               
            }
           
            // -- загрузка юзер-листа
            item = searchNode(root, "/settings/accounts/");
            if (item != null) {
                NodeList nl = item.getElementsByTagName("user");
                for (int i = 0; i < nl.getLength(); ++i) {
                    Element usr = (Element)nl.item(i);
                    long id = Long.parseLong(usr.getAttribute("id"));
                    UserItemValue userItem = new UserItemValue(id);
                    userItem.xmlImportFromNode(usr);
                    //userItem.loadOrdersHistory();
                    addUser(userItem);
                }
                lstUsers.updateUI();
            }
           
        } catch (Exception e) {
            e.printStackTrace();
        }
       
        // -- подгрузка валют с Центробанка РФ
        List<SettingsXMLFile.CurrencyItemCBRF> list = SettingsXMLFile.getCurrencyCBRF();
        if (list != null && !list.isEmpty()) {
            double vl;
            vl = SettingsXMLFile.CurrencyItemCBRF.getCurrencyValue("USD", list);
            if (vl != 0.0) convUSDRUR = vl;
            vl = SettingsXMLFile.CurrencyItemCBRF.getCurrencyValue("EUR", list);
            if (vl != 0.0) convEURRUR = vl;
            Document doc = settingsLoadXML();
            Element root = doc.getDocumentElement();
            Element item = searchNode(root, "/settings/currencyValues", true);
            item.setAttribute("usd", Double.toString(convUSDRUR));
            item.setAttribute("eur", Double.toString(convEURRUR));
            settingsSaveXML();
        }
       
        txtUSDValue.setText(Double.toString(convUSDRUR));
        txtEURValue.setText(Double.toString(convEURRUR));
    }
   
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnGroupCrazy = new javax.swing.ButtonGroup();
        pmUsers = new javax.swing.JPopupMenu();
        miEditAccount = new javax.swing.JMenuItem();
        miShowStatistics = new javax.swing.JMenuItem();
        bgTaskTime = new javax.swing.ButtonGroup();
        pnlGeneral = new javax.swing.JPanel();
        pnlGenList = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        pnlGenAction = new javax.swing.JPanel();
        pnlTrading = new javax.swing.JPanel();
        lblSelectedUser = new javax.swing.JLabel();
        spOrders = new javax.swing.JScrollPane();
        lstOrders = new javax.swing.JTable();
        lblGoSettings = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        lstTaskList = new javax.swing.JTable();
        lblCreateTask = new javax.swing.JLabel();
        txtUserNameEditor = new javax.swing.JTextField();
        lblCurrentTime = new javax.swing.JLabel();
        pnlTradeTools = new javax.swing.JPanel();
        pnlToolTrading = new javax.swing.JPanel();
        jLabel22 = new javax.swing.JLabel();
        txtChangeSL = new javax.swing.JTextField();
        jLabel23 = new javax.swing.JLabel();
        txtChangeTP = new javax.swing.JTextField();
        jLabel24 = new javax.swing.JLabel();
        txtChangePrice = new javax.swing.JTextField();
        jLabel25 = new javax.swing.JLabel();
        txtChangeTrailing = new javax.swing.JTextField();
        lblDoModify = new javax.swing.JLabel();
        pnlTradeNewOrder = new javax.swing.JPanel();
        lblGoTrading = new javax.swing.JLabel();
        lblGoNewOrder = new javax.swing.JLabel();
        pnlCreateTask = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        btnCreateTask = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        lstNewOrders = new javax.swing.JTable();
        lblAddOrder = new javax.swing.JLabel();
        lblDeleteOrder = new javax.swing.JLabel();
        lblClearOrders = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtTaskName = new javax.swing.JTextField();
        chkUseBreakeven = new javax.swing.JCheckBox();
        txtTaskTime = new javax.swing.JFormattedTextField();
        txtTaskDate = new javax.swing.JFormattedTextField();
        rbTimeStart = new javax.swing.JRadioButton();
        rbStartNow = new javax.swing.JRadioButton();
        lblCreateTaskAccCnt = new javax.swing.JLabel();
        pnlSettings = new javax.swing.JPanel();
        btnExitSettings = new javax.swing.JButton();
        tpSettings = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        rbCrazyCtrl = new javax.swing.JRadioButton();
        rbCrazyAlt = new javax.swing.JRadioButton();
        rbCrazyShift = new javax.swing.JRadioButton();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        spnOrderSendSeconds = new javax.swing.JSpinner();
        jLabel9 = new javax.swing.JLabel();
        jLabel18 = new javax.swing.JLabel();
        spnMaxTasks = new javax.swing.JSpinner();
        jLabel3 = new javax.swing.JLabel();
        txtUSDValue = new javax.swing.JTextField();
        jLabel19 = new javax.swing.JLabel();
        jLabel20 = new javax.swing.JLabel();
        txtEURValue = new javax.swing.JTextField();
        jLabel21 = new javax.swing.JLabel();
        lblPkgCounter = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane6 = new javax.swing.JScrollPane();
        lstSymbols = new javax.swing.JList();
        txtSybmolName = new javax.swing.JTextField();
        lblAddSmb = new javax.swing.JLabel();
        tbLogPane = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtLogText = new javax.swing.JTextArea();
        pnlUserEditor = new javax.swing.JPanel();
        lblAccEdit = new javax.swing.JLabel();
        txtUserName = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        btnSaveAccData = new javax.swing.JButton();
        btnCancelAccEdit = new javax.swing.JButton();
        jLabel12 = new javax.swing.JLabel();
        txtTraderComission = new javax.swing.JSpinner();
        jLabel13 = new javax.swing.JLabel();
        lblRemoveAccount = new javax.swing.JLabel();
        pnlStatistics = new javax.swing.JPanel();
        lblStatistics = new javax.swing.JLabel();
        btnCloseStatistics = new javax.swing.JButton();
        lblStatBalance = new javax.swing.JLabel();
        lblStatBalanceUSD = new javax.swing.JLabel();
        lblStatBalanceRUR = new javax.swing.JLabel();
        jLabel15 = new javax.swing.JLabel();
        lblStatProfitUSD = new javax.swing.JLabel();
        lblStatProfitRUR = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        lblStatEquity = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        lblStatOpenProfit = new javax.swing.JLabel();
        lblStatProfitPerc = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        jLabel17 = new javax.swing.JLabel();

        pmUsers.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
                pmUsersPopupMenuWillBecomeVisible(evt);
            }
        });

        miEditAccount.setIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/building_edit.png"))); // NOI18N
        miEditAccount.setText("Редактировать аккаунт");
        miEditAccount.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miEditAccountActionPerformed(evt);
            }
        });
        pmUsers.add(miEditAccount);

        miShowStatistics.setIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/money.png"))); // NOI18N
        miShowStatistics.setText("Статистика");
        miShowStatistics.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miShowStatisticsActionPerformed(evt);
            }
        });
        pmUsers.add(miShowStatistics);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Pending Script Console");
        setLocationByPlatform(true);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });
        getContentPane().setLayout(new java.awt.CardLayout());

        pnlGenList.setLayout(new java.awt.BorderLayout());

        lstUsers.setComponentPopupMenu(pmUsers);
        lstUsers.setDragEnabled(true);
        lstUsers.setVisibleRowCount(12);
        lstUsers.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lstUsersMouseClicked(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                lstUsersMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(lstUsers);

        pnlGenList.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        pnlGenAction.setLayout(new java.awt.CardLayout());

        lblSelectedUser.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblSelectedUser.setText("Ничего не выбрано");
        lblSelectedUser.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblSelectedUserMouseClicked(evt);
            }
        });

        spOrders.setBackground(new java.awt.Color(255, 255, 255));
        spOrders.setOpaque(false);
        spOrders.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                spOrdersMousePressed(evt);
            }
        });

        lstOrders.setGridColor(new java.awt.Color(204, 204, 204));
        lstOrders.setOpaque(false);
        lstOrders.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        spOrders.setViewportView(lstOrders);

        lblGoSettings.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblGoSettings.setIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/iconSettings1.png"))); // NOI18N
        lblGoSettings.setText("Настройки");
        lblGoSettings.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblGoSettingsMouseClicked(evt);
            }
        });

        jLabel4.setForeground(new java.awt.Color(102, 102, 102));
        jLabel4.setText("Задачи");

        lstTaskList.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Задача", "Статус"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane3.setViewportView(lstTaskList);

        lblCreateTask.setForeground(new java.awt.Color(0, 0, 102));
        lblCreateTask.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblCreateTask.setIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/newTask2.png"))); // NOI18N
        lblCreateTask.setText("<html><u>Создать задачу</u></html>");
        lblCreateTask.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblCreateTaskMouseClicked(evt);
            }
        });

        txtUserNameEditor.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        txtUserNameEditor.setHorizontalAlignment(javax.swing.JTextField.LEFT);
        txtUserNameEditor.setText("test");
        txtUserNameEditor.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(180, 180, 180)));
        txtUserNameEditor.setMargin(new java.awt.Insets(2, 4, 2, 2));
        txtUserNameEditor.setPreferredSize(new java.awt.Dimension(96, 18));
        txtUserNameEditor.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtUserNameEditorFocusLost(evt);
            }
        });
        txtUserNameEditor.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtUserNameEditorKeyReleased(evt);
            }
        });

        lblCurrentTime.setForeground(new java.awt.Color(105, 105, 105));
        lblCurrentTime.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblCurrentTime.setText("time: 12:30:00");

        pnlTradeTools.setLayout(new java.awt.CardLayout());

        jLabel22.setText("Stoploss:");

        txtChangeSL.setText("0.0 pt");

        jLabel23.setText("Takeprofit:");

        txtChangeTP.setText("0.0 pt");

        jLabel24.setText("Price:");

        txtChangePrice.setEditable(false);
        txtChangePrice.setText("1.3132");

        jLabel25.setText("Trailing:");

        txtChangeTrailing.setEditable(false);
        txtChangeTrailing.setText("75");

        lblDoModify.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblDoModify.setIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/tick.png"))); // NOI18N
        lblDoModify.setText("Применить");
        lblDoModify.setMinimumSize(new java.awt.Dimension(75, 20));

        javax.swing.GroupLayout pnlToolTradingLayout = new javax.swing.GroupLayout(pnlToolTrading);
        pnlToolTrading.setLayout(pnlToolTradingLayout);
        pnlToolTradingLayout.setHorizontalGroup(
            pnlToolTradingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlToolTradingLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlToolTradingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel22)
                    .addComponent(jLabel24))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlToolTradingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtChangeSL)
                    .addComponent(txtChangePrice, javax.swing.GroupLayout.DEFAULT_SIZE, 86, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(pnlToolTradingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(pnlToolTradingLayout.createSequentialGroup()
                        .addComponent(jLabel23)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtChangeTP, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(pnlToolTradingLayout.createSequentialGroup()
                        .addComponent(jLabel25)
                        .addGap(18, 18, 18)
                        .addComponent(txtChangeTrailing)))
                .addGap(18, 18, 18)
                .addComponent(lblDoModify, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(86, Short.MAX_VALUE))
        );
        pnlToolTradingLayout.setVerticalGroup(
            pnlToolTradingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlToolTradingLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlToolTradingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel22)
                    .addComponent(txtChangeSL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel23)
                    .addComponent(txtChangeTP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblDoModify, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(pnlToolTradingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtChangePrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel24)
                    .addComponent(jLabel25)
                    .addComponent(txtChangeTrailing, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(22, 22, 22))
        );

        pnlTradeTools.add(pnlToolTrading, "pnlToolTrading");

        javax.swing.GroupLayout pnlTradeNewOrderLayout = new javax.swing.GroupLayout(pnlTradeNewOrder);
        pnlTradeNewOrder.setLayout(pnlTradeNewOrderLayout);
        pnlTradeNewOrderLayout.setHorizontalGroup(
            pnlTradeNewOrderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 495, Short.MAX_VALUE)
        );
        pnlTradeNewOrderLayout.setVerticalGroup(
            pnlTradeNewOrderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 79, Short.MAX_VALUE)
        );

        pnlTradeTools.add(pnlTradeNewOrder, "pnlTradeNewOrder");

        lblGoTrading.setForeground(new java.awt.Color(102, 102, 102));
        lblGoTrading.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblGoTrading.setText("Торговля");
        lblGoTrading.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 8));
        lblGoTrading.setName("pnlToolTrading"); // NOI18N
        lblGoTrading.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblGoNewOrderMouseClicked(evt);
            }
        });

        lblGoNewOrder.setForeground(new java.awt.Color(102, 102, 102));
        lblGoNewOrder.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblGoNewOrder.setText("Новый ордер");
        lblGoNewOrder.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 8));
        lblGoNewOrder.setName("pnlTradeNewOrder"); // NOI18N
        lblGoNewOrder.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblGoNewOrderMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout pnlTradingLayout = new javax.swing.GroupLayout(pnlTrading);
        pnlTrading.setLayout(pnlTradingLayout);
        pnlTradingLayout.setHorizontalGroup(
            pnlTradingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlTradingLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlTradingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 593, Short.MAX_VALUE)
                    .addComponent(spOrders)
                    .addGroup(pnlTradingLayout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblCreateTask, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(pnlTradingLayout.createSequentialGroup()
                        .addComponent(lblCurrentTime)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlTradingLayout.createSequentialGroup()
                        .addGroup(pnlTradingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(pnlTradingLayout.createSequentialGroup()
                                .addComponent(lblSelectedUser)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtUserNameEditor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(pnlTradeTools, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(pnlTradingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(lblGoTrading, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblGoSettings, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE)
                            .addComponent(lblGoNewOrder, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))
        );
        pnlTradingLayout.setVerticalGroup(
            pnlTradingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlTradingLayout.createSequentialGroup()
                .addGap(1, 1, 1)
                .addGroup(pnlTradingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblSelectedUser)
                    .addComponent(lblGoSettings, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtUserNameEditor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlTradingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlTradingLayout.createSequentialGroup()
                        .addComponent(lblGoTrading, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblGoNewOrder, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(pnlTradeTools, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(spOrders, javax.swing.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblCurrentTime)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlTradingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(lblCreateTask, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pnlGenAction.add(pnlTrading, "pnlTrading");

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(102, 102, 102));
        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/newTask2.png"))); // NOI18N
        jLabel5.setText("Настройка новой задачи");

        jButton1.setText("Отмена");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        btnCreateTask.setText("Запустить");
        btnCreateTask.setToolTipText("Создание и запуск задачи");
        btnCreateTask.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCreateTaskActionPerformed(evt);
            }
        });

        lstNewOrders.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Symbol", "Type", "Size", "Deviation", "Stoploss", "Takeprofit", "Trailing", "Time"
            }
        ));
        lstNewOrders.setGridColor(new java.awt.Color(180, 180, 180));
        lstNewOrders.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        lstNewOrders.getTableHeader().setReorderingAllowed(false);
        jScrollPane4.setViewportView(lstNewOrders);

        lblAddOrder.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblAddOrder.setIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/iconAdd.png"))); // NOI18N
        lblAddOrder.setText("Добавить");
        lblAddOrder.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblAddOrderMouseClicked(evt);
            }
        });

        lblDeleteOrder.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblDeleteOrder.setIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/iconDelete.png"))); // NOI18N
        lblDeleteOrder.setText("Удалить");
        lblDeleteOrder.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblDeleteOrderMouseClicked(evt);
            }
        });

        lblClearOrders.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblClearOrders.setIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/iconClear1.png"))); // NOI18N
        lblClearOrders.setText("Очистить");
        lblClearOrders.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblClearOrdersMouseClicked(evt);
            }
        });

        jLabel2.setText("Имя задачи:");

        txtTaskName.setText("Новая задача");

        chkUseBreakeven.setSelected(true);
        chkUseBreakeven.setText("Выставлять безубыток");
        chkUseBreakeven.setToolTipText("Трейлинг на минимально возможном количестве пунктов (stoplevel)");
        chkUseBreakeven.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/chk_iconDisabled.png"))); // NOI18N
        chkUseBreakeven.setDisabledSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/chk_selIconDisabled.png"))); // NOI18N
        chkUseBreakeven.setEnabled(false);
        chkUseBreakeven.setIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/chk_icon.png"))); // NOI18N
        chkUseBreakeven.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/chk_iconMoused.png"))); // NOI18N
        chkUseBreakeven.setRolloverSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/chk_selIconMoused.png"))); // NOI18N
        chkUseBreakeven.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/chk_selIcon.png"))); // NOI18N
        chkUseBreakeven.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                chkUseBreakevenStateChanged(evt);
            }
        });
        chkUseBreakeven.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkUseBreakevenActionPerformed(evt);
            }
        });

        txtTaskTime.setColumns(6);
        try {
            MaskFormatter mfX = new javax.swing.text.MaskFormatter("##:##:##");
            mfX.setPlaceholderCharacter('0');
            txtTaskTime.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(mfX));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txtTaskTime.setText("12:29:30");
        txtTaskTime.setName("timeInput"); // NOI18N

        txtTaskDate.setColumns(8);
        try {
            MaskFormatter mfX = new javax.swing.text.MaskFormatter("####.##.##");
            mfX.setPlaceholderCharacter('0');
            txtTaskDate.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(mfX));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txtTaskDate.setText("2013.11.15");
        txtTaskDate.setName("dateInput"); // NOI18N

        bgTaskTime.add(rbTimeStart);
        rbTimeStart.setSelected(true);
        rbTimeStart.setText("Время запуска:");
        rbTimeStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbTimeStartActionPerformed(evt);
            }
        });

        bgTaskTime.add(rbStartNow);
        rbStartNow.setText("Запустить сразу");
        rbStartNow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbStartNowActionPerformed(evt);
            }
        });

        lblCreateTaskAccCnt.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        lblCreateTaskAccCnt.setForeground(new java.awt.Color(102, 0, 102));
        lblCreateTaskAccCnt.setText("Счетов выбрано: ни одного");

        javax.swing.GroupLayout pnlCreateTaskLayout = new javax.swing.GroupLayout(pnlCreateTask);
        pnlCreateTask.setLayout(pnlCreateTaskLayout);
        pnlCreateTaskLayout.setHorizontalGroup(
            pnlCreateTaskLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlCreateTaskLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlCreateTaskLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlCreateTaskLayout.createSequentialGroup()
                        .addGroup(pnlCreateTaskLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane4)
                            .addGroup(pnlCreateTaskLayout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(pnlCreateTaskLayout.createSequentialGroup()
                                .addComponent(lblAddOrder, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(lblDeleteOrder, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(lblClearOrders, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(chkUseBreakeven)))
                        .addContainerGap())
                    .addGroup(pnlCreateTaskLayout.createSequentialGroup()
                        .addGroup(pnlCreateTaskLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnlCreateTaskLayout.createSequentialGroup()
                                .addGap(21, 21, 21)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtTaskName))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnlCreateTaskLayout.createSequentialGroup()
                                .addComponent(rbTimeStart)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtTaskDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtTaskTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(rbStartNow)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, Short.MAX_VALUE)
                        .addGroup(pnlCreateTaskLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlCreateTaskLayout.createSequentialGroup()
                                .addComponent(btnCreateTask)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlCreateTaskLayout.createSequentialGroup()
                                .addComponent(lblCreateTaskAccCnt)
                                .addContainerGap())))))
        );
        pnlCreateTaskLayout.setVerticalGroup(
            pnlCreateTaskLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlCreateTaskLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 297, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnlCreateTaskLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblAddOrder, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblDeleteOrder, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblClearOrders, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(chkUseBreakeven))
                .addGap(18, 18, 18)
                .addGroup(pnlCreateTaskLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtTaskTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtTaskDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(rbTimeStart)
                    .addComponent(rbStartNow)
                    .addComponent(lblCreateTaskAccCnt))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlCreateTaskLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(btnCreateTask)
                    .addComponent(jLabel2)
                    .addComponent(txtTaskName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        pnlGenAction.add(pnlCreateTask, "pnlCreateTask");

        btnExitSettings.setText("OK");
        btnExitSettings.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitSettingsActionPerformed(evt);
            }
        });

        jLabel1.setText("Защита от дурака");

        btnGroupCrazy.add(rbCrazyCtrl);
        rbCrazyCtrl.setSelected(true);
        rbCrazyCtrl.setText("Ctrl");

        btnGroupCrazy.add(rbCrazyAlt);
        rbCrazyAlt.setText("Alt");

        btnGroupCrazy.add(rbCrazyShift);
        rbCrazyShift.setText("Shift");

        jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/crazy2.gif"))); // NOI18N

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel7)
                .addGap(18, 18, 18)
                .addComponent(rbCrazyCtrl)
                .addGap(18, 18, 18)
                .addComponent(rbCrazyAlt)
                .addGap(18, 18, 18)
                .addComponent(rbCrazyShift)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(rbCrazyCtrl)
                        .addComponent(rbCrazyAlt)
                        .addComponent(rbCrazyShift)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel8.setText("Отправка ордеров за");
        jLabel8.setToolTipText("Автоподбор времени с периодом 15 минут. Нужно указать за сколько секунд до конца периода будет выставлено время отправки.");

        spnOrderSendSeconds.setModel(new javax.swing.SpinnerNumberModel(20, 5, 120, 1));
        spnOrderSendSeconds.setToolTipText("Автоподбор времени с периодом 15 минут. Нужно указать за сколько секунд до конца периода будет выставлено время отправки.");

        jLabel9.setText("сек");
        jLabel9.setToolTipText("Автоподбор времени с периодом 15 минут. Нужно указать за сколько секунд до конца периода будет выставлено время отправки.");

        jLabel18.setText("Максимум задач в списке");
        jLabel18.setToolTipText("Максимальное количество задач, которое будет отображаться в таблице на торговой панели");

        spnMaxTasks.setModel(new javax.swing.SpinnerNumberModel(25, 4, 128, 1));
        spnMaxTasks.setToolTipText("Максимальное количество задач, которое будет отображаться в таблице на торговой панели");

        jLabel3.setText("Актуальный курс USD");

        txtUSDValue.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtUSDValue.setText("32.9");
        txtUSDValue.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtUSDValueActionPerformed(evt);
            }
        });

        jLabel19.setText("рублей");

        jLabel20.setText("Актуальный курс EUR");

        txtEURValue.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtEURValue.setText("40");

        jLabel21.setText("рублей");

        lblPkgCounter.setText("package count: 0");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(lblPkgCounter))
                    .addComponent(jLabel1)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jLabel8)
                                    .addComponent(jLabel18, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel20, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(spnMaxTasks, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(spnOrderSendSeconds, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel9))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(txtEURValue, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel21))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(txtUSDValue, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel19)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 315, Short.MAX_VALUE)))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(23, 23, 23)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(spnOrderSendSeconds, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel9)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(spnMaxTasks, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel18))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtUSDValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel19)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtEURValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel21)
                    .addComponent(jLabel20))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 142, Short.MAX_VALUE)
                .addComponent(lblPkgCounter)
                .addContainerGap())
        );

        tpSettings.addTab("Основные", jPanel1);

        jLabel6.setText("Работа программы будет ограничена введёнными валютными парами");

        lstSymbols.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "eurusd", "gbpusd", "eurgbp", "audusd", "usdcad", "usdjpy" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        lstSymbols.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lstSymbols.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jScrollPane6.setViewportView(lstSymbols);

        txtSybmolName.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
        txtSybmolName.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtSybmolNameKeyReleased(evt);
            }
        });

        lblAddSmb.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblAddSmb.setIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/iconAdd.png"))); // NOI18N
        lblAddSmb.setText("Добавить");
        lblAddSmb.setEnabled(false);
        lblAddSmb.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblAddSmbMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(txtSybmolName, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblAddSmb, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jLabel6))
                .addContainerGap(211, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane6, javax.swing.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(txtSybmolName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblAddSmb, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        tpSettings.addTab("Валютные пары", jPanel2);

        txtLogText.setColumns(20);
        txtLogText.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        txtLogText.setRows(5);
        txtLogText.setText("Neiro Technology 2011-2014\n\nPending Script Console Log\n");
        jScrollPane2.setViewportView(txtLogText);

        javax.swing.GroupLayout tbLogPaneLayout = new javax.swing.GroupLayout(tbLogPane);
        tbLogPane.setLayout(tbLogPaneLayout);
        tbLogPaneLayout.setHorizontalGroup(
            tbLogPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 578, Short.MAX_VALUE)
        );
        tbLogPaneLayout.setVerticalGroup(
            tbLogPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE)
        );

        tpSettings.addTab("Logs", tbLogPane);

        javax.swing.GroupLayout pnlSettingsLayout = new javax.swing.GroupLayout(pnlSettings);
        pnlSettings.setLayout(pnlSettingsLayout);
        pnlSettingsLayout.setHorizontalGroup(
            pnlSettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlSettingsLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlSettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlSettingsLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnExitSettings))
                    .addComponent(tpSettings))
                .addContainerGap())
        );
        pnlSettingsLayout.setVerticalGroup(
            pnlSettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlSettingsLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(tpSettings)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnExitSettings)
                .addContainerGap())
        );

        pnlGenAction.add(pnlSettings, "pnlSettings");

        lblAccEdit.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblAccEdit.setForeground(new java.awt.Color(102, 102, 102));
        lblAccEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/building_edit.png"))); // NOI18N
        lblAccEdit.setText("Редактирование данных аккаунта \"18343\"");

        txtUserName.setText("Теряев Леонид Леонидович");

        jLabel11.setText("Имя клиента");

        btnSaveAccData.setText("ОК");
        btnSaveAccData.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveAccDataActionPerformed(evt);
            }
        });

        btnCancelAccEdit.setText("Отмена");
        btnCancelAccEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelAccEditActionPerformed(evt);
            }
        });

        jLabel12.setText("Комиссия трейдера");

        txtTraderComission.setModel(new javax.swing.SpinnerNumberModel(Byte.valueOf((byte)50), Byte.valueOf((byte)10), Byte.valueOf((byte)90), Byte.valueOf((byte)1)));

        jLabel13.setText("%");

        lblRemoveAccount.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblRemoveAccount.setIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/user_delete.png"))); // NOI18N
        lblRemoveAccount.setText("Удалить счёт из списка");
        lblRemoveAccount.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblRemoveAccountMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout pnlUserEditorLayout = new javax.swing.GroupLayout(pnlUserEditor);
        pnlUserEditor.setLayout(pnlUserEditorLayout);
        pnlUserEditorLayout.setHorizontalGroup(
            pnlUserEditorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlUserEditorLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlUserEditorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlUserEditorLayout.createSequentialGroup()
                        .addGroup(pnlUserEditorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(pnlUserEditorLayout.createSequentialGroup()
                                .addComponent(lblAccEdit)
                                .addGap(0, 212, Short.MAX_VALUE))
                            .addGroup(pnlUserEditorLayout.createSequentialGroup()
                                .addComponent(lblRemoveAccount, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnSaveAccData)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancelAccEdit))
                    .addGroup(pnlUserEditorLayout.createSequentialGroup()
                        .addGroup(pnlUserEditorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(pnlUserEditorLayout.createSequentialGroup()
                                .addComponent(jLabel12)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtTraderComission, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel13))
                            .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel11))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        pnlUserEditorLayout.setVerticalGroup(
            pnlUserEditorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlUserEditorLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblAccEdit)
                .addGap(30, 30, 30)
                .addComponent(jLabel11)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(pnlUserEditorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(txtTraderComission, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel13))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 275, Short.MAX_VALUE)
                .addGroup(pnlUserEditorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSaveAccData)
                    .addComponent(btnCancelAccEdit)
                    .addComponent(lblRemoveAccount, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pnlGenAction.add(pnlUserEditor, "pnlUserEditor");

        lblStatistics.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblStatistics.setForeground(new java.awt.Color(102, 102, 102));
        lblStatistics.setIcon(new javax.swing.ImageIcon(getClass().getResource("/psconsole/resources/money.png"))); // NOI18N
        lblStatistics.setText("Статистика");

        btnCloseStatistics.setText("OK");
        btnCloseStatistics.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseStatisticsActionPerformed(evt);
            }
        });

        lblStatBalance.setText("Баланс:");
        lblStatBalance.setToolTipText("Текущий суммарный баланс для выбранных аккаунтов");

        lblStatBalanceUSD.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblStatBalanceUSD.setText("666 USD");

        lblStatBalanceRUR.setForeground(new java.awt.Color(102, 102, 102));
        lblStatBalanceRUR.setText("= 21512 RUR");

        jLabel15.setText("Прибыль:");
        jLabel15.setToolTipText("Профит вычисляется с предыдущего расчётного периода");

        lblStatProfitUSD.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblStatProfitUSD.setText("0 USD");

        lblStatProfitRUR.setForeground(new java.awt.Color(102, 102, 102));
        lblStatProfitRUR.setText("= 0 RUR");

        jLabel10.setForeground(new java.awt.Color(102, 102, 102));
        jLabel10.setText("Средства:");
        jLabel10.setToolTipText("Суммарные средства по выбранным счетам");

        lblStatEquity.setForeground(new java.awt.Color(102, 102, 102));
        lblStatEquity.setText("666 USD");

        jLabel16.setForeground(new java.awt.Color(102, 102, 102));
        jLabel16.setText("Профит:");
        jLabel16.setToolTipText("Прибыль по открытым позициям");

        lblStatOpenProfit.setForeground(new java.awt.Color(102, 102, 102));
        lblStatOpenProfit.setText("0 USD");

        lblStatProfitPerc.setText("(0.00%)");

        jLabel14.setText("Комиссия:");
        jLabel14.setToolTipText("Комиссия трейдера с учётом процентных ставок каждого из выбранных счетов");

        jLabel17.setText("0 USD");

        javax.swing.GroupLayout pnlStatisticsLayout = new javax.swing.GroupLayout(pnlStatistics);
        pnlStatistics.setLayout(pnlStatisticsLayout);
        pnlStatisticsLayout.setHorizontalGroup(
            pnlStatisticsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlStatisticsLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlStatisticsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlStatisticsLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnCloseStatistics))
                    .addGroup(pnlStatisticsLayout.createSequentialGroup()
                        .addComponent(lblStatistics)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(pnlStatisticsLayout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addGroup(pnlStatisticsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlStatisticsLayout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addGroup(pnlStatisticsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel15)
                            .addComponent(lblStatBalance))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(pnlStatisticsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(pnlStatisticsLayout.createSequentialGroup()
                                .addComponent(lblStatBalanceUSD)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblStatBalanceRUR))
                            .addGroup(pnlStatisticsLayout.createSequentialGroup()
                                .addComponent(lblStatProfitUSD)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblStatProfitPerc)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblStatProfitRUR))))
                    .addGroup(pnlStatisticsLayout.createSequentialGroup()
                        .addGroup(pnlStatisticsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel14)
                            .addComponent(jLabel10)
                            .addComponent(jLabel16))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(pnlStatisticsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblStatEquity)
                            .addComponent(lblStatOpenProfit)
                            .addComponent(jLabel17))))
                .addContainerGap(384, Short.MAX_VALUE))
        );
        pnlStatisticsLayout.setVerticalGroup(
            pnlStatisticsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlStatisticsLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblStatistics)
                .addGap(18, 18, 18)
                .addGroup(pnlStatisticsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblStatBalance)
                    .addComponent(lblStatBalanceUSD)
                    .addComponent(lblStatBalanceRUR))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlStatisticsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(lblStatProfitUSD)
                    .addComponent(lblStatProfitRUR)
                    .addComponent(lblStatProfitPerc))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlStatisticsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel14)
                    .addComponent(jLabel17))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlStatisticsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(lblStatEquity))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlStatisticsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel16)
                    .addComponent(lblStatOpenProfit))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 271, Short.MAX_VALUE)
                .addComponent(btnCloseStatistics)
                .addContainerGap())
        );

        pnlGenAction.add(pnlStatistics, "pnlStatistics");

        javax.swing.GroupLayout pnlGeneralLayout = new javax.swing.GroupLayout(pnlGeneral);
        pnlGeneral.setLayout(pnlGeneralLayout);
        pnlGeneralLayout.setHorizontalGroup(
            pnlGeneralLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlGeneralLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlGenList, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlGenAction, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        pnlGeneralLayout.setVerticalGroup(
            pnlGeneralLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlGeneralLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlGeneralLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(pnlGenAction, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(pnlGenList, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        getContentPane().add(pnlGeneral, "pnlGeneral");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void lblCreateTaskMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblCreateTaskMouseClicked
        int i = (Integer)spnOrderSendSeconds.getModel().getValue();
        String s = sdfCurrentTime.format(getCorrectedTime(i));
        StringTokenizer st = new StringTokenizer(s, " ");
        txtTaskDate.setText(st.nextToken());
        txtTaskTime.setText(st.nextToken());
        showGenAction("pnlCreateTask");
    }//GEN-LAST:event_lblCreateTaskMouseClicked

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        showGenAction("pnlTrading");
    }//GEN-LAST:event_jButton1ActionPerformed

    private void lblAddOrderMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblAddOrderMouseClicked
        //TaskOrder order = new TaskOrder("gbpusd");
        taskOTM.addOrder();
    }//GEN-LAST:event_lblAddOrderMouseClicked

    private void lblDeleteOrderMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblDeleteOrderMouseClicked
        for (int i = taskOTM.getRowCount() - 1; i >= 0; --i)
            if (lstNewOrders.isRowSelected(i)) taskOTM.removeOrder(i, false);
        taskOTM.rowsRemoved(new TableModelEvent(taskOTM));
    }//GEN-LAST:event_lblDeleteOrderMouseClicked

    private void lblClearOrdersMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblClearOrdersMouseClicked
        taskOTM.clear();
    }//GEN-LAST:event_lblClearOrdersMouseClicked

    private void lblGoSettingsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblGoSettingsMouseClicked
        showGenAction("pnlSettings");
    }//GEN-LAST:event_lblGoSettingsMouseClicked

    private void btnExitSettingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitSettingsActionPerformed
        // сохранение параметров в файл
        try {
            Document doc = settingsLoadXML();
            Element root = doc.getDocumentElement();
            Element item;
            NodeList nl;
            int i = 0;

            // -- сохранение вкладки Основные
            item = searchNode(root, "/settings/general/crazy", true);
            if (rbCrazyAlt.isSelected()) i = 1;
            else if (rbCrazyCtrl.isSelected()) i = 2;
            else if (rbCrazyShift.isSelected()) i = 3;
            item.setAttribute("ind", Integer.toString(i));

            // -- сохранение символов
            item = searchNode(root, "/settings/symbols/", true);
            nl = item.getChildNodes();
            for (i = nl.getLength() - 1; i >= 0; --i)
                item.removeChild(nl.item(i));
            symbolList.exportToXML(item);
           
            // -- Время до отправки ордеров
            i = (Integer)spnOrderSendSeconds.getModel().getValue();
            searchNode(root, "/settings/timeSecOffset", true).setAttribute("sec", Integer.toString(i));

            settingsSaveXML();
           
            // отправка терминалам обновлённого списка символов
            sendSymbolsToClients();           
        } catch (Exception e) { e.printStackTrace(); }
       
        // отображение торговой страницы
        showGenAction("pnlTrading");
    }//GEN-LAST:event_btnExitSettingsActionPerformed

    private void txtSybmolNameKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSybmolNameKeyReleased
        if (evt.getKeyChar() == '\n') {
            lblAddSmbMouseClicked(null);
            return;
        }
        txtSymbolNameKeyUp(evt);
        String s = txtSybmolName.getText();
        if (s.isEmpty()) { if (lblAddSmb.isEnabled()) lblAddSmb.setEnabled(false); }
        else { if (!lblAddSmb.isEnabled()) lblAddSmb.setEnabled(true); }
        Symbol smb = symbolList.search(s, true);
        if (smb == null) {
            lblAddSmb.setIcon(iconAdd);
            lblAddSmb.setText("Добавить");
        } else if (s.equalsIgnoreCase(smb.symbol)) {
            lblAddSmb.setIcon(iconRemove);
            lblAddSmb.setText("Удалить");
        }
    }//GEN-LAST:event_txtSybmolNameKeyReleased

    private void txtSymbolNameKeyUp(KeyEvent evt) {
        String s = txtSybmolName.getText();
        if (!Character.isLetter(evt.getKeyChar()) || txtSybmolName.getCaretPosition() < s.length())
            return;
        if (s.isEmpty()) return;
        Symbol smb = symbolList.search(s);
        String sb = (smb == null ? null : smb.symbol);
        if (sb == null) return;
        String add = sb.substring(s.length());
        txtSybmolName.setText(s + add);
        txtSybmolName.setSelectionStart(s.length());
        txtSybmolName.setSelectionEnd(s.length() + add.length());
    }
   
    private void lblAddSmbMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblAddSmbMouseClicked
        if (!lblAddSmb.isEnabled()) return;
        String s = txtSybmolName.getText();
        Symbol smb = symbolList.search(s, true);
        if (smb == null) {
            symbolList.add(s);
            txtSybmolName.setText("");
        } else if (s.equalsIgnoreCase(smb.symbol)) {
            symbolList.remove(smb);
            txtSybmolName.setText("");
        }
        lblAddSmb.setEnabled(false);
    }//GEN-LAST:event_lblAddSmbMouseClicked

    private void txtUserNameEditorKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUserNameEditorKeyReleased
        if (evt.getKeyChar() == '\n') {
            List<UserItemValue> items = getSelectedUsers();
            if (items.size() == 1 && items.get(0).accountID != -1) {
                items.get(0).name = txtUserNameEditor.getText();
                lblSelectedUser.setText(txtUserNameEditor.getText() + " [" + items.get(0).accountID + "]");
                lstUsers.repaint();
            }
            setUserNameEditMode(false);
            return;
        } else if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
            setUserNameEditMode(false);
            return;
        }
        JTextField txt = txtUserNameEditor;
        FontMetrics fm = txt.getGraphics().getFontMetrics();
        int x = fm.stringWidth(txt.getText()) + 6;
        if (x < 96) x = 96;
        txt.setSize(x, txt.getHeight());
        txt.setPreferredSize(txt.getSize());
    }//GEN-LAST:event_txtUserNameEditorKeyReleased

    private void lblSelectedUserMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblSelectedUserMouseClicked
        if (checkCrazy(evt)) setUserNameEditMode(true);
    }//GEN-LAST:event_lblSelectedUserMouseClicked

    private void txtUserNameEditorFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtUserNameEditorFocusLost
        setUserNameEditMode(false);
    }//GEN-LAST:event_txtUserNameEditorFocusLost

    private void btnCreateTaskActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateTaskActionPerformed
       
        long tm = 0;
        //<editor-fold desc=" проверки на корректность ">
        try {
            tm = sdfCurrentTime.parse(txtTaskDate.getText() + " " + txtTaskTime.getText()).getTime();
        } catch (ParseException pe) { pe.printStackTrace(); }
        if (tm < timeCurrent && rbTimeStart.isSelected()) {
            DialogForm dlg = new DialogForm(
                    new DialogForm.DialogData("Время введено некорректно!",
                    "Время запуска задачи указано с запозданием или некорректно!", this, true));
            dlg.setVisible(true);
            return;
        }
       
        List<UserItemValue> selUsers = getSelectedUsers();
        if (selUsers.isEmpty()) {
            DialogForm dlg = new DialogForm(
                    new DialogForm.DialogData("Не выбран ни один счёт для рассылки задачи",
                    "Счета выбираются в списке слева. Чтобы выбрать всё сразу,"
                    + " надо кликнуть только по первому элементу списка!", this, true));
            dlg.setVisible(true);
            return;
        }
        if (taskOTM.getRowCount() < 1) {
            DialogForm dlg = new DialogForm(
                    new DialogForm.DialogData("Нельзя создать пустую задачу",
                    "Чтобы добавить ордера, щёлкай на кнопку \"Добавить\" ниже таблицы!", this, true));
            dlg.setVisible(true);
            return;
        }
        boolean flag = true;
        for (int col = 0; col < taskOTM.getColumnCount(); ++col) {
            for (int row = 0; row < taskOTM.getRowCount(); ++row)
                flag &= taskOTM.validateCell(
                        taskOTM.getValueAt(row, col), row, col);
        }
        if (!flag) {
            DialogForm dlg = new DialogForm(
                    new DialogForm.DialogData("Невозможно создать задачу",
                    "В таблице ордеров есть некорректно введённые данные!", this, true));
            dlg.setVisible(true);
            return;
        }
        //</editor-fold>
       
        // -- заполняем объект задачи
        Task task = new Task(numsys.geterateID());
        for (int i = 0; i < taskOTM.count(); ++i) {
            TaskOrder o = taskOTM.getOrder(i);
            task.orderList.add(o);
        }
        task.name = txtTaskName.getText();
        task.startNow = rbStartNow.isSelected();
        task.timeStart = task.startNow ? timeCurrent : tm;
       
        // -- добавление спика привязанных к задаче аккаунтов
        for (UserItemValue usr : getSelectedUsers()) {
            TaskManager.TaskAccInfo info = new TaskManager.TaskAccInfo(usr.accountID);
            info.lastTimeSending = 0;
            info.status = TaskManager.TaskAccInfo.TS_Sending;
            task.accountList.add(info);
        }
       
        taskManager.addTask(task);
        taskModel.refreshTaskList(taskManager);
        showGenAction("pnlTrading");
    }//GEN-LAST:event_btnCreateTaskActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        try {
            Document doc = settingsLoadXML();
            Element root = doc.getDocumentElement();
            Element item;

            // -- сохранение положения окна
            item = searchNode(root, "/settings/general/bounds", true);
            item.setAttribute("left", Integer.toString(this.getX()));
            item.setAttribute("top", Integer.toString(this.getY()));
            item.setAttribute("width", Integer.toString(this.getWidth()));
            item.setAttribute("height", Integer.toString(this.getHeight()));
           
            // -- сохранение списка юзверей
            item = searchNode(root, "/settings/accounts/", true);
            NodeList nl = item.getChildNodes();
            for (int i = nl.getLength() - 1; i >= 0; --i) item.removeChild(nl.item(i));
            for (UserItemValue acc : getAllUsers()) {
                acc.xmlExportToNode(item);
                //acc.saveOrdersHistory();
            }
        } catch (Exception e) { e.printStackTrace(); }
        settings.stop();
        server.stop();
    }//GEN-LAST:event_formWindowClosing

    private void chkUseBreakevenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkUseBreakevenActionPerformed
        int[] selRows = lstNewOrders.getSelectedRows();
        chkUseBreakeven.setIcon(chbox_icon);
        chkUseBreakeven.setRolloverIcon(chbox_iconMoused);
        for (int i = 0; i < selRows.length; ++i)
            taskOTM.getOrder(selRows[i]).useBreakeven = chkUseBreakeven.isSelected();
    }//GEN-LAST:event_chkUseBreakevenActionPerformed

    private void chkUseBreakevenStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_chkUseBreakevenStateChanged
       
    }//GEN-LAST:event_chkUseBreakevenStateChanged

    private void miEditAccountActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miEditAccountActionPerformed
        onUserSelected(getSelectedUsers(), "pnlUserEditor");
        showGenAction("pnlUserEditor");
    }//GEN-LAST:event_miEditAccountActionPerformed

    private void pmUsersPopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_pmUsersPopupMenuWillBecomeVisible
        miEditAccount.setEnabled(getSelectedUsers().size() == 1);
    }//GEN-LAST:event_pmUsersPopupMenuWillBecomeVisible

    private void btnSaveAccDataActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveAccDataActionPerformed
        List<UserItemValue> selection = getSelectedUsers();
        if (selection.size() != 1) return;
        UserItemValue user = selection.get(0);
        user.name = txtUserName.getText();
        user.traderComission = ((Byte)txtTraderComission.getValue()).byteValue();
        showGenAction("pnlTrading");
    }//GEN-LAST:event_btnSaveAccDataActionPerformed

    private void btnCancelAccEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelAccEditActionPerformed
        showGenAction("pnlTrading");
    }//GEN-LAST:event_btnCancelAccEditActionPerformed

    private void lstUsersMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstUsersMouseClicked
        if (evt.getButton() == 3) {
            //lstUsers.get
        }
    }//GEN-LAST:event_lstUsersMouseClicked

    private void lblRemoveAccountMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblRemoveAccountMouseClicked
        List<UserItemValue> selection = getSelectedUsers();
        if (selection.size() != 1) return;
        UserItemValue user = selection.get(0);
        if (DialogForm.showMessage("Удаление аккаунта", "Подтвердите, "
                + "действительно ли вы хотите удалить аккаунт \"" + user.accountID
                + "\" из базы?", "Да", "Нет", this) != DialogForm.RET_OK) return;
        listModel.removeElement(user);
        lstUsers.updateUI();
        saveUserList();
        showGenAction("pnlTrading");
    }//GEN-LAST:event_lblRemoveAccountMouseClicked

    private void miShowStatisticsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miShowStatisticsActionPerformed
        showGenAction("pnlStatistics");
    }//GEN-LAST:event_miShowStatisticsActionPerformed

    private void btnCloseStatisticsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseStatisticsActionPerformed
        showGenAction("pnlTrading");
    }//GEN-LAST:event_btnCloseStatisticsActionPerformed

    private void lstUsersMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstUsersMousePressed
        if (evt.getButton() != MouseEvent.BUTTON3) return;
        int index = lstUsers.locationToIndex(evt.getPoint());
        if (evt.isControlDown()) lstUsers.addSelectionInterval(index, index);
        else lstUsers.setSelectedIndex(index);
    }//GEN-LAST:event_lstUsersMousePressed

    private void rbStartNowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbStartNowActionPerformed
        txtTaskDate.setEnabled(!rbStartNow.isSelected());
        txtTaskTime.setEnabled(!rbStartNow.isSelected());
    }//GEN-LAST:event_rbStartNowActionPerformed

    private void rbTimeStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbTimeStartActionPerformed
        txtTaskDate.setEnabled(rbTimeStart.isSelected());
        txtTaskTime.setEnabled(rbTimeStart.isSelected());
    }//GEN-LAST:event_rbTimeStartActionPerformed

    private void txtUSDValueActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtUSDValueActionPerformed
       
    }//GEN-LAST:event_txtUSDValueActionPerformed

    private void spOrdersMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_spOrdersMousePressed
        if (evt.getButton() == MouseEvent.BUTTON1)
            lstOrders.clearSelection();
    }//GEN-LAST:event_spOrdersMousePressed

    private void lblGoNewOrderMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblGoNewOrderMouseClicked
        JLabel l = (JLabel)evt.getComponent();
        CardLayout cl = (CardLayout)pnlTradeTools.getLayout();
        cl.show(pnlTradeTools, l.getName());
    }//GEN-LAST:event_lblGoNewOrderMouseClicked
   
    public String getJarFileName() {
        Class mainClass = MainForm.class;
        String name = mainClass.getName().replace('.', '/');
        name = "/" +name+ ".class";
        URL url = mainClass.getResource(name);
        return url.getFile();
    }
   
    private void initImages() {
        URL icoURL = null;
        try {
            userActive1 = getIconByName("userActive1.png");
            userActive2 = getIconByName("userActive2.png");
            userActive3 = getIconByName("userActive3.png");
            iconAdd = getIconByName("iconAdd.png");
            iconRemove = getIconByName("iconDelete.png");
            chbox_icon = getIconByName("chk_icon.png");
            chbox_iconMoused = getIconByName("chk_iconMoused.png");
            chbox_other = getIconByName("chk_otherIcon.png");
            chbox_otherMoused = getIconByName("chk_otherIconMoused.png");
        } catch (Exception e) { e.printStackTrace(); }
    }
   
    // -- загрузка иконки из ресурсов (по имени)
    private ImageIcon getIconByName(String name) throws Exception {
        URL icoURL = getClass().getResource("/psconsole/resources/" + name);
        if (icoURL != null) return new ImageIcon(icoURL);
        else return null;
    }
   
    private boolean checkCrazy(java.awt.event.MouseEvent evt) {
        return (evt.isControlDown() && rbCrazyCtrl.isSelected()) ||
                (evt.isAltDown() && rbCrazyAlt.isSelected()) ||
                (evt.isShiftDown() && rbCrazyShift.isSelected());
    }
   
    /**
     * Поиск объекта в списке по номеру счёта.
     * @return null, если такого объекта нет
     */
    public UserItemValue getUser(long accID) {
        if (accID < 1) return null;
        for (int i = 0; i < listModel.getSize(); ++i) {
            UserItemValue vl = (UserItemValue)listModel.get(i);
            if (vl.accountID == accID) return vl;
        }
        return null;
    }
   
    /**
     * Добавляет новый элемент в список терминалов
     * @param item созданный новый элемент
     */
    public void addUser(UserItemValue item) {
        listModel.addElement(item);
    }
   
    /**
     * выдаёт все выделенные элементы lstUsers
     * @return пустой ArrayList, если список пуст
     */
    public List<UserItemValue> getSelectedUsers() {
        int[] obj = lstUsers.getSelectedIndices();
        ArrayList<UserItemValue> res = new ArrayList<>();
        boolean flag = false;
        for (int i = 0; i < obj.length; ++i) {
            if (listModel.get(obj[i]).accountID == -1) {
                flag = true;
                break;
            }
            res.add(listModel.get(obj[i]));
        }
        // -- если в списке выделенных есть общий элемент, то выделенными считать надо все элементы
        if (flag) {
            res.clear();
            for (int i = 0; i < listModel.getSize(); ++i)
                if (listModel.get(i).accountID != -1) res.add(listModel.get(i));
        }
        return res;
    }
   
    /**
     * Возвращает полный список торговых счетов
     * @return ArrayList.isEmpty()==true, если список пуст (не null)
     */
    public List<UserItemValue> getAllUsers() {
        ArrayList<UserItemValue> res = new ArrayList<>();
        for (int i = 0; i < listModel.getSize(); ++i)
            if (listModel.get(i).accountID != -1) res.add(listModel.get(i));
        return res;
    }
   
    /**
     * Обрабатывает выбор элементов в списке счетов
     * @param selection выбранные счета
     * @param paneCard имя панели, для которой следует провести обработку
     */
    public void onUserSelected(List<UserItemValue> selection, String paneCard) {
        switch (paneCard) {
           
            case "pnlTrading":
                // -- выводим выделение в Label
                String s;
                if (selection.size() == 1) {
                    s = selection.get(0).name + " [" + selection.get(0).accountID + "]";
                } else if (selection.size() > 1) {
                    s = "";
                    for (UserItemValue o : selection)
                        s = s + (s.isEmpty() ? "" : ", ") + o.accountID;
                } else s = "Ничего не выбрано";
                lblSelectedUser.setText(s);
                ordersModel.refreshData();
                break;
               
            case "pnlCreateTask":
                btnCreateTask.setEnabled(selection.size() > 0);
                if (selection.isEmpty())
                    lblCreateTaskAccCnt.setText("Счетов выбрано: ни одного");
                else if (selection.size() == getAllUsers().size())
                    lblCreateTaskAccCnt.setText("Счетов выбрано: все");
                else lblCreateTaskAccCnt.setText("Счетов выбрано: " +
                        selection.size() + "/" + getAllUsers().size());
                break;
               
            case "pnlSettings":
                break;
               
            case "pnlUserEditor":
                List<UserItemValue> selUsers = selection;
                boolean flag = selUsers.size() == 1;
                lblAccEdit.setEnabled(flag);
                txtUserName.setEnabled(flag);
                txtTraderComission.setEnabled(flag);
                btnSaveAccData.setEnabled(flag);
                lblRemoveAccount.setEnabled(flag);
                if (flag) {
                    lblAccEdit.setText("Редактирование данных аккаунта \""
                            + selUsers.get(0).accountID + "\"");
                    txtUserName.setText(selUsers.get(0).name);
                    txtTraderComission.setValue(new Byte(selUsers.get(0).traderComission));
                } else {
                    lblAccEdit.setText("Редактирование данных аккаунта");
                    txtUserName.setText("Выберите один счёт!");
                    txtTraderComission.setValue(new Byte((byte)0));
                }
                break;
               
            case "pnlStatistics":
                double b = 0.0, p = 0.0, pCurr = 0.0, eq, bInit = 0.0;
                List<UserItemValue> users = getSelectedUsers();
               
                for (UserItemValue i : users) {
                    b += i.balance;
                    p += i.getProfit();
                    bInit += i.getInitialBalance();
                    pCurr += i.profit;
                }
                eq = b + pCurr;
               
                lblStatBalanceUSD.setText(getCurrencyStr(b) + " USD");
                lblStatBalanceRUR.setText(getCurrencyStr(b * convUSDRUR) + " RUR");
               
                lblStatProfitUSD.setText(getCurrencyStr(p) + " USD");
                lblStatProfitPerc.setText("(" + getCurrencyStr(p / bInit * 100) + "%)");
                lblStatProfitRUR.setText(getCurrencyStr(p * convUSDRUR) + " RUR");
               
                lblStatEquity.setText(getCurrencyStr(eq) + " USD");
                lblStatOpenProfit.setText(getCurrencyStr(pCurr) + " USD");
               
                break;
               
        }
    }
   
    /**
     * Форматирование дробного числа с тысячными разделителями (пробел) <br>
     * Дробный разделитель - точка '.'
     * @param value денежная сумма
     * @return String формата "12 345 678.09"
     */
    public String getCurrencyStr(double value) {
        boolean isNegative = value < 0.0;
        if (isNegative) value *= -1.0;
        long x = (long)(value * 100);
        long m = x % 100;
        String dr = "";
        if (m < 1);
        else if (m % 10 == 0) dr = "." + (m / 10);
        else dr = "." + (m >= 10 ? Long.toString(m) : "0" + m);
       
        StringBuilder s = new StringBuilder(Long.toString(x / 100));
        StringBuilder n = new StringBuilder();
        while (s.length() > 0) {
            if (n.length() > 0) n.insert(0, ' ');
            int i = s.length() - 3;
            if (i < 0) i = 0;
            n.insert(0, s.substring(i, s.length()));
            s.delete(i, s.length());
        }
        if (isNegative) n.insert(0, '-');
        return n.toString() + dr;
    }
   
    /**
     * Корректное преобразование дробного числа в строку с указанием кол-ва цифр
     * @param value значение
     * @param digits количество цифр после запятой
     * @return string-число, которое может быть распарсено классом Double
     */
    public static String doubleToStr(double value, int digits) {
        /*double mult = digits > 0 ? Math.pow(10, digits) : 1d;
        long x = (long)(value * mult);
        String s = Long.toString(x);
        StringBuilder sb = new StringBuilder();
       
        if (digits > 0) {
            sb.append('.');
            sb.append(s.substring(s.length() - digits, s.length()));
            s = s.substring(0, s.length() - digits);
        }
       
        sb.insert(0, s);*/
       
        return String.format(Locale.US, "%1." + digits + "f", value);
    }
   
    /**
     * Вывести/скрыть элемент редактирования имени клиента
     * @param isEditing и так понятно
     */
    public void setUserNameEditMode(boolean isEditing) {
        if (!isEditing) {
            txtUserNameEditor.setVisible(false);
            lblSelectedUser.setVisible(true);
        } else {
            List<UserItemValue> items = getSelectedUsers();
            if (items.size() != 1 || items.get(0).accountID == -1) return;
            lblSelectedUser.setVisible(false);
            txtUserNameEditor.setText(items.get(0).name);
            txtUserNameEditor.setVisible(true);
            txtUserNameEditor.requestFocus();
            txtUserNameEditor.selectAll();
        }
    }
   
    public void showGenAction(String name) {
        CardLayout lt = (CardLayout)pnlGenAction.getLayout();
        onUserSelected(getSelectedUsers(), name);
        lt.show(pnlGenAction, name);
        panePrev = paneCurrent;
        paneCurrent = name;
    }
   
    /**
     * Изменение яркости цвета
     * @param color исходный цвет
     * @param size на какое кол-во менять цвет (по шкале 0..255)
     * @return результирующий цвет
     */
    public Color changeColor(Color color, int size) {
        int r = color.getRed() + size;
        int g = color.getGreen() + size;
        int b = color.getBlue() + size;
        if (r < 0) r = 0; else if (r > 255) r = 255;
        if (g < 0) g = 0; else if (g > 255) g = 255;
        if (b < 0) b = 0; else if (b > 255) b = 255;
        return new Color(r, g, b);
    }
   
    public Document settingsLoadXML() {
        return settings.getDocument();
    }
   
    /**
     * Поиск элемента по пути
     * @param root корновой элемент, с которого начинается поиск
     * @param path путь к элементу. Имена тегов разделяются знаком "/"
     * @param canCreate разрешение на создание элементов. Например, если существует
     * путь <b>"/ex1/ex2/"</b>, но будет запрошен путь <b>"/ex1/ex2/ex3/ex4/"</b>,
     * то если <b>canCreate == true</b>, остаток пути <b>"/ex3/ex4/"</b> будет
     * создан.
     * @return null, если элемент не найден
     */
    public Element searchNode(Element root, String path, boolean canCreate) {
        StringTokenizer st = new StringTokenizer(path, "/");
        Element x = root;
        while (st.hasMoreTokens()) {
            String tag = st.nextToken();
            NodeList nl = x.getElementsByTagName(tag);
            if (nl.getLength() == 0) {
                if (!canCreate) {
                    x = null;
                    break;
                } else {
                    Element a = root.getOwnerDocument().createElement(tag);
                    x.appendChild(a);
                    x = a;
                }
            } else x = (Element)nl.item(0);
        }
        return x;
    }
   
    public Element searchNode(Element root, String path) {
        return searchNode(root, path, false);
    }
   
    /**
     * Сохраняет xml-документ в файл с настройками
     * @param doc заполненный настройками документ
     */
    public void settingsSaveXML() {
        settings.saveSettings(false);
    }
   
    /**
     * Сохранение списка торговых счетов в settings (XML)
     */
    public void saveUserList() {
        try {
            Document doc = settingsLoadXML();
            Element root = doc.getDocumentElement();
            Element item;

            // -- сохранение списка юзеров
            item = searchNode(root, "/settings/accounts/", true);
            NodeList nl = item.getChildNodes();
            for (int i = nl.getLength() - 1; i >= 0; --i) item.removeChild(nl.item(i));
            for (UserItemValue acc : getAllUsers())
                acc.xmlExportToNode(item);

            settingsSaveXML();
        } catch (Exception e) { e.printStackTrace(); }
    }
   
    /**
     * Возвращает путь к папке скрипта. Если папка не существует, то она будет создана
     * @return путь к папке
     */
    public static String getScriptDirectory() {
        String dir = System.getProperty("user.home") + "/Neiro Technology/PS Console";
        File dr = new File(dir);
        if (!dr.exists()) dr.mkdirs();
        return dir;
    }
   
    /**
     * Возвращает адрес директории для хранения истории ордеров
     * @return путь без слеша в конце
     */
    public static String getOrdersHistoryDir() {
        String fl = getScriptDirectory() + "/Orders History";
        File dir = new File(fl);
        if (!dir.exists()) dir.mkdirs();
        return fl;
    }
   
    /**
     * Устанавливает новое время сервера, если текущее меньше этого нового.
     * Автоматически выводит это время в лейбл на торговой панели и в заголовок
     * формы.
     * @param tm время сервера в миллисекундах (GMT+0)
     */
    public void setCurrentTime(long tm) {
        tmManager.setTime(tm);
    }
   
    /**
     * Вызывается менеджером времени раз в секунду
     */
    public void onTimeCurrent() {
        lblCurrentTime.setText("time: " + sdfCurrentTime.format(timeCurrent));
        setTitle("Pending Script Console [ " + sdfCurrentTime.format(timeCurrent) + " ]");
    }
   
    /**
     * Выдаёт скорректированное время за несколько секунд до конца теущего
     * 15-минутного периода
     * @param secondsOffset количество секунд до конца периода
     * @return сдвинутое к концу периода время, идёт в том же формате, что
     *      и <b>timeCurrent</b>
     */
    public long getCorrectedTime(int secondsOffset) {
        Calendar c = timeCurrentCalendar;
        final int period = 15*60;
        c.setTimeInMillis(timeCurrent);
        int sec = c.get(Calendar.MINUTE) * 60 + c.get(Calendar.SECOND) - 1;
        int buff = ((sec / period) + 1) * period;
        int rs = buff - sec - secondsOffset - 1;
        if (rs < 0) rs += period;
        return timeCurrent + rs*1000;
    }
   
    /**
     * Обновление списка открытых ордеров
     */
    public void refreshOrderList() {/*
        List<UserItemValue> users = getSelectedUsers();
        if (users.isEmpty()) {
            ordersModel.clear();
            lstOrders.updateUI();
            return;
        }
        OrderItem<OrderData> order;
        // -- удаление старой информации
        for (int i = 0; i < ordersModel.getRowCount(); ++i) {
            order = (OrderItem<OrderData>)ordersModel.getValueAt(i, 0);
            order.data.count = 0;
            order.data.flag = false;
        }
        // -- обновление модели
        Object[] rowData = new Object[ordersModel.getColumnCount()];
        for (UserItemValue user : users) {
            OrderList list = user.orders;
            for (int i = 0; i < list.count(); ++i) {
                // -- если ордер принадлежит какой-то задаче
                if (list.get(i).taskID != null) {
                    int thID = list.get(i).taskID.hashCode();
                    int oID = list.get(i).orderIDTask;
                    order = ordersModel.orderDataExists(thID, oID);
                    if (order == null) {
                        order = new OrderItem<>(0, list.get(i).instrument);
                        rowData[0] = order;
                        order.data = new OrderData(list.get(i).orderIDTask, list.get(i).taskID);
                        ordersModel.addRow(rowData);
                    }
                    order.data.count += 1;
                } else { // если не принадлежит ни одной задаче
                    order = new OrderItem<>(0, list.get(i).instrument);
                    rowData[0] = order;
                    order.data = new OrderData(0, "");
                    ordersModel.addRow(rowData);
                }
            }
        }
        lstOrders.updateUI();*/
    }
   
    /**
     * Рассылка актуального списка листов клиентам.
     */
    public void sendSymbolsToClients() {
        PSPackage pkg = new PSPackage("symbol-update");
        pkg.set("symbols", symbolList.getSymbolList());
        List<ServerConsole.Terminal> connections = server.getConnectionsList();
        for (ServerConsole.Terminal t : connections)
            t.sendPackage(pkg);
    }
   
    /**
     * Валидация значения цены stoploss или takeprofit. Цена может указываться
     * в пунктах (например, "40pt"), или в отношении валют (рыночной цене)
     * @param s строка, которая должна пройти проверку
     * @return null, если значение не валидно, иначе, PriceStoploss, заполненный
     * правильными данными
     */
    public PriceStoploss validateStopPrice(String s) {
        if (s == null) return null;
        if (s.isEmpty()) return new PriceStoploss(0, 1);
        String buf = s.toLowerCase();
        int i = buf.indexOf("pt");
        if (i < 0) {
            try {
                double db = Double.parseDouble(s.trim());
                return new PriceStoploss(db, 1);
            } catch (Exception e) {
                return null;
            }
        }
        StringTokenizer st = new StringTokenizer(buf.substring(0, i)
                + " " + buf.substring(i + 1));
        if (st.countTokens() != 2) return null;
        try {
            buf = st.nextToken();
            if (!st.nextToken().equals("pt")) return null;
            return new PriceStoploss(Double.parseDouble(buf), 0);
        } catch (Exception e) {}
        return null;
    }
   
    public ServerConsole server;
    public final SettingsXMLFile settings;
    private final Random random;
    private final LabelHighligher lblHighligh;
   
    private final DefaultListModel<UserItemValue> listModel;
    private final DefaultListModel<Symbol> listModelSmb;
    public  final SymbolList symbolList;
    private final UserItemRenderer pnlRenderUsers;
   
    public final TaskTableModel taskModel;
    public final TaskTableCellRenderer taskCellRenderer;
   
    private final TaskOrdersTableModel taskOTM;
   
    private final OrdersTableModel ordersModel;
    private final OrdersTableCellRenderer ordersRenderer;
   
    // Current Server Time  MT4 (GMT+00)
    public volatile long timeCurrent;
    public final SimpleDateFormat sdfCurrentTime;
    public final Calendar timeCurrentCalendar;
   
    // -- редактор валютной пары
    private final JTextField txtSymbolEditor;
   
    // значение USD/RUR
    public double convUSDRUR;
    public double convEURRUR;
   
    // -- иконки
    private ImageIcon userActive1, userActive2, userActive3;
    private ImageIcon iconAdd, iconRemove;
    private ImageIcon chbox_icon, chbox_iconMoused, chbox_other, chbox_otherMoused;
   
   
    // -- pane cards
    public String panePrev;   
    public String paneCurrent;
   
    // -- менеджер времени
    private final TimeManager tmManager;
    // -- менеджер задач
    public final TaskManager taskManager;
   
    public final NumeralSystems numsys;
   
   
    private static class OrderTableHeaderRenderer implements TableCellRenderer {

        DefaultTableCellRenderer renderer;

        public OrderTableHeaderRenderer(JTable table) {
            renderer = (DefaultTableCellRenderer)
                table.getTableHeader().getDefaultRenderer();
            renderer.setHorizontalAlignment(JLabel.CENTER);
        }

        @Override
        public Component getTableCellRendererComponent(
                JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int col) {
            if (col == 0) renderer.setHorizontalAlignment(JLabel.LEFT);
            else renderer.setHorizontalAlignment(JLabel.RIGHT);
            return renderer.getTableCellRendererComponent(
                table, value, isSelected, hasFocus, row, col);
        }
    }
    private class LabelHighligher extends MouseAdapter {
        public final Color hglg = new Color(255, 255, 255);
        public final int r2, g2, b2;
       
        private final long timeUp = 100;
        private final long timeDown = 200;

        public LabelHighligher() {
            items = new ArrayList<>();
            r2 = hglg.getRed();
            g2 = hglg.getGreen();
            b2 = hglg.getBlue();
           
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(50);
                            EventQueue.invokeAndWait(new Runnable() {
                                @Override
                                public void run() {
                                    synchronized (items) {
                                        Iterator<Item> i = items.iterator();
                                        while (i.hasNext())
                                            if (i.next().doCalc()) i.remove();
                                    }
                                }
                            });
                        } catch (Exception e) {}
                    }
                }
            });
            t.start();
        }
       
        @Override
        public void mouseEntered(MouseEvent e) {
            if (!(e.getComponent() instanceof JLabel)) return;
            JLabel lbl = (JLabel)e.getComponent();
            /*if (!lbl.isEnabled()) return;
            lbl.setBackground(hglg);
            lbl.setOpaque(true);
            lbl.repaint();*/
           
            setLabelState(lbl, true);
        }
      
        @Override
        public void mouseExited(MouseEvent e) {
            if (!(e.getComponent() instanceof JLabel)) return;
            JLabel lbl = (JLabel)e.getComponent();
            /*lbl.setOpaque(false);
            lbl.repaint();*/
           
            setLabelState(lbl, false);
        }
       
        public void setLabelState(JLabel label, boolean isInc) {
            synchronized (items) {
                Item item = null;
                for (Item i : items)
                    if (i.label == label) {
                        item = i;
                        break;
                    }
                if (item == null) {
                    item = new Item(label, isInc);
                    items.add(item);
                }
                item.isIncrement = isInc;
            }
        }
       
        private final List<Item> items;
       
        private class Item {
            public int r1, g1, b1;
            public boolean isIncrement;
            public final JLabel label;
            public long time;
           
            public Item(JLabel label, boolean isIncrement) {
                this.label = label;
                Color c = label.getParent().getBackground();
                r1 = c.getRed();
                g1 = c.getGreen();
                b1 = c.getBlue();
                this.isIncrement = isIncrement;
                time = System.currentTimeMillis();
            }
           
            /**
             * Вычисляет цвет подсветки лейбла
             * @return true, если подсветка завершена, и требуется удаление
             */
            public boolean doCalc() {
                int r, g, b;
                boolean res = false;
                double p = (System.currentTimeMillis() - time) /
                        (double)(isIncrement ? timeUp : timeDown);
                if (p >= 1.0 || p <= 0.0) res = true;
                if (p > 1.0) p = 1.0;
                else if (p < 0.0) p = 0.0;
                if (!isIncrement) p = 1.0 - p;
                r = (int)(r1 + p * (r2 - r1));
                g = (int)(g1 + p * (g2 - g1));
                b = (int)(b1 + p * (b2 - b1));
                if (label.isVisible()) {
                    if (!label.isOpaque()) label.setOpaque(true);
                    label.setBackground(new Color(r, g, b));
                    //label.repaint();
                }
                if (res && !isIncrement) label.setOpaque(false);
                return res;
            }
        }
    }
   
    /**
     * Cell Renderer для таблицы задач в панели трейдинга.
     */
    public class TaskTableCellRenderer extends DefaultTableCellRenderer {

        public TaskTableCellRenderer() {
            super();
            label = new JLabel();
            label.setBorder(new EmptyBorder(0, 4, 0, 4));
        }
       
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
            label.setText(value == null ? "null" : value.toString());
            label.setOpaque(isSelected);
            if (isSelected) label.setBackground(Color.LIGHT_GRAY);
            else label.setBackground(Color.white);
            return label;
        }
       
        private final JLabel label;
    }
   
    public class TaskTableModel extends DefaultTableModel {
       
        public TaskTableModel(Object[] columns) {
            super(columns, 0);
        }
       
        @Override
        public Object getValueAt(int row, int column) {
            Object res = null;
            Task task = getTask(row);
            if (column == 0) res = task.name + ", " + sdfCurrentTime.format(task.timeStart);
            else if (column == 1) res = task.id;
            else if (column == 2) res = task.status.description;
            return res;
        }
       
        @Override
        public void setValueAt(Object aValue, int row, int column) {
            if (column > 0) return;
            super.setValueAt(aValue, row, column);
        }
       
        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
       
        public int getTaskCount() {
            return getRowCount();
        }
       
        public Task getTask(int index) {
            return (Task)super.getValueAt(index, 0);
        }
       
        public boolean containTask(Task task) {
            for (int i = 0; i < getTaskCount(); ++i)
                if (task == getTask(i)) return true;
            return false;
        }
       
        public void refreshTaskList(TaskManager taskManager) {
            int n = (Integer)spnMaxTasks.getValue();
            int i = 0;
            boolean flag = false;
            Object[] row = {null, null};
            synchronized (taskManager.taskList) {
                for (Task task : taskManager.taskList) {
                    if (!containTask(task)) {
                        row[0] = task;
                        insertRow(0, row);
                        flag = true;
                    }
                }
            }
            while (getTaskCount() > n) remove(n);
            if (flag) newRowsAdded(new TableModelEvent(this));
            newDataAvailable(new TableModelEvent(this));
        }
    }
   
    /**
     * Отрисовщик элементов для таблицы ордеров задачи (в панели создания задачи)
     */
    private class TaskOrdersTableCellRenderer extends DefaultTableCellRenderer {
       
        public TaskOrdersTableCellRenderer() {
            super();
            emptyBorder = new EmptyBorder(2, 2, 1, 1);
            lineBorder = new LineBorder(new Color(180, 200, 255), 1, false);
            //lineBorder.
            lblRenderer = new JLabel();
            lblRenderer.setOpaque(true);
            lblRenderer.setBorder(emptyBorder);
        }
       
        private Color doRed(int count, Color c) {
            int r = c.getRed() + count, g = c.getGreen() - count,
                    b = c.getBlue() - count;
            if (r > 255) r = 255; else if (r < 0) r = 0;
            if (g > 255) g = 255; else if (g < 0) g = 0;
            if (b > 255) b = 255; else if (b < 0) b = 0;
            return new Color(r, g, b);
        }
       
        private final int redChange = 50;
        private final EmptyBorder emptyBorder;
        private final LineBorder lineBorder;
       
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
            lblRenderer.setText(value.toString());
            lblRenderer.setForeground(Color.black);
            //lblRenderer.setBorder(hasFocus ? lineBorder : emptyBorder);
            Color bkg = isSelected ? selectedColor : Color.white;
            if (!taskOTM.validateCell(value, row, column))
                bkg = doRed(redChange, bkg);
            lblRenderer.setBackground(bkg);
            return lblRenderer;
        }
       
        private final Color selectedColor = new Color(223, 223, 223);
        private final JLabel lblRenderer;
    }
   
    /**
     * Модель таблицы новой задачи
     */
    private class TaskOrdersTableModel extends DefaultTableModel {
       
        public TaskOrdersTableModel(Object[][] data, Object[] columnNames) {
            super(data, columnNames);
        }
       
        @Override
        public boolean isCellEditable(int row, int column) {
            return true;
        }
       
        /**
         * Removing all rows
         */
        public void clear() {
            while (getRowCount() > 0) removeRow(0);
            this.rowsRemoved(new TableModelEvent(this));
        }
       
        /**
         * Возвращает количество ордеров
         * @return 0, если таблица пуста
         */
        public int count() {
            return getRowCount();
        }
       
        /**
         * Возвращает ордер по номеру
         * @param index индекс строки, в которой расположен ордер
         */
        public TaskOrder getOrder(int index) {
            return (TaskOrder)super.getValueAt(index, 0);
        }
       
        /**
         * Добавить строку с ордером
         * @param order ордер, который будет связан со строкой
         */
        public void addOrder(TaskOrder order) {
            Object[] rowData = new Object[getColumnCount()];
            rowData[0] = order;
            for (int i = 1; i < rowData.length; ++i) rowData[i] = null;
            this.addRow(rowData);
        }
       
        /**
         * Добавляет новый ордер и новую строку, и связывает их
         * @return созданный функцией ордер (дефолтным конструктором)
         */
        public TaskOrder addOrder() {
            TaskOrder order = new TaskOrder("gbpusd");
            addOrder(order);
            return order;
        }
       
        public boolean removeOrder(int index, boolean generateEvent) {
            try {
                removeRow(index);
                if (generateEvent) rowsRemoved(new TableModelEvent(this));
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }
       
        public boolean removeOrder(TaskOrder order, boolean generateEvent) {
            for (int i = 0; i < getRowCount(); ++i)
                if (order == getOrder(i)) return removeOrder(i, generateEvent);
            return false;
        }
       
        @Override
        public Object getValueAt(int row, int column) {
            TaskOrder order = getOrder(row);
            switch (column) {
                case 0: return order;
                case 1: return order.type;
                case 2: return order.size;
                case 3: return order.deviation;
                case 4: return order.stoploss;
                case 5: return order.takeprofit;
                case 6: return order.trailing;
                case 7: return order.time;
                default: return null;
            }
            //return super.getValueAt(row, column);
        }
       
        @Override
        public void setValueAt(Object aValue, int row, int column) {
            boolean valid = validateCell(aValue, row, column);
            TaskOrder order = getOrder(row);
            switch (column) {
                case 0: order.symbol = aValue.toString(); break;
                case 1: order.type = (TaskOrder.Type)aValue; break;
                case 2:
                    if (valid) order.size = Double.parseDouble(aValue.toString());
                    //else order.size = 10.0;
                    break;
                case 3: case 4: case 5: case 6: case 7:
                    try {
                        int vl = Integer.parseInt(aValue.toString());
                        if (column == 3) order.deviation = vl;
                        else if (column == 4) order.stoploss = vl;
                        else if (column == 5) order.takeprofit = vl;
                        else if (column == 6) order.trailing = vl;
                        else if (column == 7) order.time = vl;
                    } catch (Exception e) {}
                    break;
            }
        }
       
        /**
         * Валидация значения ячейки
         * @param aValue новое значение ячейки
         * @param row индекс строки
         * @param column индекс столбца
         * @return true, если значение допустимо для указанной ячейки
         */
        public boolean validateCell(Object aValue, int row, int column) {
            switch (column) {
                case 0:
                    Symbol smb = symbolList.search(aValue.toString(), true);
                    return smb != null;
               
                case 1: try { return aValue instanceof TaskOrder.Type; } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
               
                case 2:
                    try {
                        double vl = Double.parseDouble(aValue.toString());
                        return vl > 0.0 && vl < 100.0;
                    } catch (Exception e) { return false; }
                   
                   
                case 3: case 4: case 5: case 6: case 7:
                   try {
                        int vl = Integer.parseInt(aValue.toString());
                        if (column < 7) {
                            Symbol sym = symbolList.search(getOrder(row).symbol, true);
                            if (vl == 0 && (column >= 4 || column <= 6)) return true;
                            else return (vl > sym.minSL);
                        } else return (vl > 0);
                    } catch (Exception e) { return false; }
               
                default: return true;
            }
        }
    }
   
    /**
     * Прорисовщик ячеек главной торговой таблицы
     */
    public class OrdersTableCellRenderer extends DefaultTableCellRenderer {
       
        //<editor-fold desc="  fields :)  ">
        private final Color clrLong = new Color(100, 135, 200);
        private final Color clrShort = new Color(220, 130, 70);
        private final Color clrSimple = new Color(45, 45, 45);
        private final Color clrSelection = new Color(220, 220, 240);
       
        private final Color clrProfitMinus = new Color(255, 85, 80);
        private final Color clrProfitPlus = new Color(0, 150, 0);
       
        private final Font font = new Font("Tahoma", 0, 11);
        private final Font fontSmb = new Font("Consolas", 0, 12);
       
        private final JLabel lbl;
        //</editor-fold>
       
        public OrdersTableCellRenderer() {
            super();
            lbl = new JLabel();
            lbl.setBorder(new EmptyBorder(2, 4, 1, 4));
            lbl.setOpaque(true);
           
        }
       
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
            OrderItem<OrderData> order = ordersModel.getOrder(row);
           
            lbl.setText(value == null ? "null" : value.toString());
           
            int align = column == 0 ? JLabel.LEFT : JLabel.RIGHT;
            if (align != lbl.getHorizontalAlignment()) lbl.setHorizontalAlignment(align);
           
            // background Color
            Color bkg = Color.white;
            if (isSelected) bkg = clrSelection;
            else if (order.data.isTaskOrder && order.data.task != null)
                bkg = order.data.task.color;
            lbl.setBackground(bkg);
           
            // назначение шрифта
            Font fnt = font;
            if (column == ordersModel.CI_Symbol) fnt = fontSmb;
            if (!lbl.getFont().equals(fnt)) lbl.setFont(fnt);
           
            // foreground Color
            if (column == ordersModel.CI_Type) {
                if (ordersModel.getOrder(row).isLong())
                    lbl.setForeground(clrLong);
                else lbl.setForeground(clrShort);
            } else if (column == ordersModel.CI_Profit) {
                if (ordersModel.getOrder(row).profit > 1d)
                    lbl.setForeground(clrProfitPlus);
                else if (ordersModel.getOrder(row).profit < -1d)
                    lbl.setForeground(clrProfitMinus);
                else lbl.setForeground(Color.gray);
            } else if (column == ordersModel.CI_ID) {
                if (order.data.isTaskOrder) lbl.setForeground(Color.gray);
            } else lbl.setForeground(clrSimple);
           
            return lbl;
        }
    }
   
    /**
     * Модель таблицы открытых позиций в торговой панели
     */
    public class OrdersTableModel extends DefaultTableModel {
       
        public final int CI_ID;
        public final int CI_Symbol;
        public final int CI_Type;
        public final int CI_Size;
        public final int CI_Price;
        public final int CI_Stoploss;
        public final int CI_Takeprofit;
        public final int CI_Trailing;
        public final int CI_Profit;
        public final int CI_Time;
        private final String emptyStr = "";
       
        public OrdersTableModel() {
            super();
            rows = new LinkedList<>();
           
            int counter = 0;
            super.addColumn("ID");
            CI_ID = counter++;
            super.addColumn("Symbol");
            CI_Symbol = counter++;
            super.addColumn("Type");
            CI_Type = counter++;
            super.addColumn("Size");
            CI_Size = counter++;
            super.addColumn("Price");
            CI_Price = counter++;
            super.addColumn("Stoploss");
            CI_Stoploss = counter++;
            super.addColumn("Takeprofit");
            CI_Takeprofit = counter++;
            super.addColumn("Trailing");
            CI_Trailing = counter++;
            super.addColumn("Profit");
            CI_Profit = counter++;
            super.addColumn("Time");
            CI_Time = counter++;
           
            users = new LinkedList<>();
        }
       
        @Override
        public Object getValueAt(int row, int column) {
            try {
                OrderItem<OrderData> order = getOrder(row);
                Symbol smb = symbolList.search(order.symbol, true);
                if (smb == null) {
                    symbolList.add(order.symbol.toLowerCase());
                    btnExitSettingsActionPerformed(null);
                }
                int dig = smb == null ? 4 : smb.digits;
                if (column == CI_Symbol) return order.symbol;
                else if (column == CI_Type)
                    return order.type;
                else if (column == CI_Size)
                    return doubleToStr(order.lots, 2);
                else if (column == CI_Price)
                    return doubleToStr(order.priceOpen, dig);
                else if (column == CI_Stoploss)
                    return order.stoploss == 0 ? emptyStr : doubleToStr(order.stoploss, dig);
                else if (column == CI_Takeprofit)
                    return order.takeprofit == 0 ? emptyStr : doubleToStr(order.takeprofit, dig);
                else if (column == CI_Trailing) {
                    if (!order.data.isTaskOrder) return emptyStr;
                    //else return order
                }
                else if (column == CI_Profit) return doubleToStr(order.profit, 2);
                else if (column == CI_Time) {
                    if (order.data.isTaskOrder) {
                        //Task task = taskManager.
                    } else return emptyStr;
                }
                else if (column == CI_ID) {
                    return order.data.isTaskOrder ?
                        order.data.taskID + "." + order.data.taskOrderIndex :
                        order.id;
                }
            } catch (Exception e) {}
            return emptyStr;
        }
       
        @Override
        public void setValueAt(Object aValue, int row, int column) {
            if (column == CI_Trailing)
                System.out.println("setTrailing: " + aValue);
        }
       
        /**
         * Возвращает ордер по индексу (строке)
         * @param index номер строки с ордером
         * @return OrderItem object
         */
        public OrderItem<OrderData> getOrder(int index) {
            return rows.get(index);
        }
       
        /**
         * Количество строк таблицы
         * @return 0, если таблица пуста, иначе - кол-во строк ( кэп (с) )
         */
        @Override
        public int getRowCount() {
            return rows == null ? 0 : rows.size();
        }
       
        @Override
        public boolean isCellEditable(int row, int column) {
            OrderItem<OrderData> order = getOrder(row);
            boolean flag = column == CI_Stoploss ||
                    column == CI_Takeprofit;
            if (order.data.isTaskOrder) flag |= column == CI_Trailing;
            //if (order.type.equals(OrderList.OrderType.OP_BUYSTOP)))
            // возможность задать объём
            return (flag);
        }
       
        /**
         * Removing all rows
         */
        public void clear() {
            rows.clear();
        }
       
        /**
         * Обновление списка ордеров
         */
        public void refreshData() {
            int ocnt = 0;
            users = getSelectedUsers();
           
            // -- получаем выделенные строки
            int[] selArr = lstOrders.getSelectedRows();
            List<OrderItem> selList = new LinkedList<>();
            for (int i = 0; i < selArr.length; ++i)
                selList.add(getOrder(selArr[i]));
           
            // необходимость генерации событий
            boolean flagNewRowsAvailable = false;
           
            // -- пробегаемся по ордерам, обнуляем счётчики аккантов
            for (int i = 0; i < getRowCount(); ++i) {
                OrderItem<OrderData> order = getOrder(i);
                order.data.count = 0;
                order.resetOrderData();
            }
           
            // -- пробегаемся по юзерам, и от каждого добавляем/обновляем табличный ордер
            //<editor-fold>
            TempData t = new TempData();
            t.canCreate = true;
            for (UserItemValue item : users) {
                ocnt += item.orders.count();
                for (int i = 0; i < item.orders.count(); ++i) {
                    OrderItem userOrder = item.orders.get(i);
                    // поиск задачи, к которой принадлежит ордер
                    ReciveOrderCheck ans = taskManager.checkTaskOrder(userOrder.comment);
                   
                    // поиск среди имеющихся ордеров
                    OrderItem<OrderData> o;
                    t.wasCreated = false;
                    if (ans == null) {
                        // если ордер не принадлежит никакой задаче
                        o = findOrderSimple(userOrder, item, t);
                        o.comment = userOrder.comment;
                        o.data.count = 1;
                    } else {
                        // если ордер принадлежит какой-то задаче
                        o = findOrderTask(userOrder, ans, t);
                        ++o.data.count;
                    }
                    o.type = userOrder.type;
                    o.lots += userOrder.lots;
                    o.profit += userOrder.profit;
                    o.priceOpen += userOrder.priceOpen;
                    o.priceClose += userOrder.priceClose;
                    o.timeOpen += userOrder.timeOpen;
                    o.timeClose += userOrder.timeClose;
                    o.stoploss += userOrder.stoploss;
                    o.takeprofit += userOrder.takeprofit;
                    if (t.wasCreated) {
                        flagNewRowsAvailable = true;
                    }
                }
            }
            //</editor-fold>
           
            // выводим среднее арифметическое параметров ордеров и ...
            // ... удаляем те ордера, count которых 0 (значит, что они уже в истории)
            //<editor-fold>
            Iterator<OrderItem<OrderData>> i = rows.iterator();
            while (i.hasNext()) {
                OrderItem<OrderData> o = i.next();
                if (o.data.count == 0) {
                    i.remove();
                    flagNewRowsAvailable = true;
                    continue;
                }
                try {
                    o.lots /= (double)o.data.count;
                    o.profit /= (double)o.data.count;
                    o.priceOpen /= (double)o.data.count;
                    o.priceClose /= (double)o.data.count;
                    o.timeOpen /= o.data.count;
                    o.timeClose /= o.data.count;
                    o.stoploss /= (double)o.data.count;
                    o.takeprofit /= (double)o.data.count;
                } catch (Exception e) {}
            }
            //</editor-fold>
           
            // если требуется, обновляем таблицу
            TableModelEvent evt = new TableModelEvent(this);
            if (flagNewRowsAvailable) {
                newRowsAdded(evt);
                //System.out.println(" new rows added !!!!!!!!! ");
            } else newDataAvailable(evt);
           
            // -- восстановление выделения
            ocnt = 0;
            DefaultListSelectionModel sm = (DefaultListSelectionModel)lstOrders.getSelectionModel();
            for (OrderItem item : selList) {
                int index = rows.indexOf(item);
                if (index >= 0) {
                    ++ocnt;
                    //lstOrders.changeSelection(index, 0, true, true);
                    sm.addSelectionInterval(index, index);
                }
            }
        }
       
        private OrderItem<OrderData> findOrderTask(OrderItem source, ReciveOrderCheck ans, TempData temp) {
            int index = 0;
            boolean isLong = source.isLong();
            int i = -1;
            for (OrderItem<OrderData> o : rows) {
                ++i;
                // если ордер не "озадаченный"
                if (!o.data.isTaskOrder) continue;
                // для сортировки
                if (source.timeOpen < o.timeOpen) index = i;
                // если id найденной задачи не совпадает с tsak-id ордера
                if (!ans.task.id.equals(o.data.taskID)) continue;
                // если индекс ордера в задаче или его тип отличается, то это не наш случай
                if (o.data.taskOrderIndex != ans.index || o.data.isLong != isLong) continue;
                return o;
            }
            if (!temp.canCreate) return null;
            OrderItem<OrderData> o;
            o = new OrderItem<>(source.id, source.symbol);
            o.data = new OrderData(-1, ans.task.id);
            o.data.isTaskOrder = true;
            o.data.taskOrderIndex = ans.index;
            o.data.task = ans.task;
            o.data.isLong = isLong;
            rows.add(index, o);
            temp.wasCreated = true;
            return o;
        }
       
        private OrderItem<OrderData> findOrderSimple(OrderItem source, UserItemValue usr, TempData temp) {
            int index = 0, i = -1;
            for (OrderItem<OrderData> o : rows) {
                ++i;
                if (o.data.isTaskOrder) continue;
                if (source.timeOpen < o.timeOpen) index = i;
                if (source.id == o.id) return o;
            }
            if (temp.canCreate) {
                OrderItem<OrderData> o;
                o = new OrderItem<>(source.id, source.symbol);
                o.data = new OrderData(usr.accountID, null);
                o.data.isTaskOrder = false;
                rows.add(index, o);
                temp.wasCreated = true;
                return o;
            }
            return null;
        }
       
       
        /**
         * Список юзеров, из которых брать сделки для обновления
         */
        public List<UserItemValue> users;
       
        private final LinkedList<OrderItem<OrderData>> rows;
       
        public class OrderData {
           
            public int count; // количство ордеров
            public boolean isLong; // true = buy, flase = sell
           
            public final String taskID; // идентификатор задачи (для озадаченных ордеров)
            /**
             * Номер ордера в задаче (если такая задача существует)
             */
            public int taskOrderIndex;
           
            public final long accID; // id аккаунта (для неозадаченных ордеров) (да, смешные коменты :D)
            public boolean isTaskOrder;
            public Task task;
           
            public OrderData(long accID, String taskID) {
                this.count = 0;
                this.accID = accID;
                this.taskID = taskID;
                isTaskOrder = true;
                taskOrderIndex = -1;
                isLong = true;
                task = null;
            }
        }
       
        private class TempData {
            boolean canCreate = true;
            boolean wasCreated = false;
        }
    }
   
    /**
     * Менеджер серверного времени
     * @author deathNC
     */
    public static class TimeManager extends Thread {

        public TimeManager(long tm, MainForm form) {
            super();
            this.form = form;
            list = new LinkedList<>();
            setTime(tm);
            setDaemon(true);
            start();
        }
       
        /**
         * Добавляет разницу между указанным временем и системным в коллекцию
         * таких разниц. Каждую секунду берётся среднее значение разницы, и на
         * его основе выводится время timeCurrent
         * @param tm текущее время сервера (не разница, а время!). Функция сама
         * посчитает разницу.
         */
        public void setTime(long tm) {
            synchronized (list) {
                list.addLast(new Long(System.currentTimeMillis() - tm));
                if (list.size() > 32) list.removeFirst();
            }
        }
       
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                    // -- вычисление средней разницы с System.currentTimeMillis
                    long t = 0;
                    synchronized (list) {
                        Iterator<Long> i = list.iterator();
                        while (i.hasNext()) t += i.next().longValue();
                    }
                    t = t / (long)list.size();
                    // -- присвоение нового времени в форме
                    final long cTime  = System.currentTimeMillis() - t;
                    EventQueue.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            form.timeCurrent = cTime;
                            form.onTimeCurrent();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
       
        private long timeDiff;
        private final LinkedList<Long> list;
        private final MainForm form;
    }
   
    public static class PriceStoploss {

        public PriceStoploss() {
            value = 0.0;
            type = 0;
        }

        public PriceStoploss(double value, int type) {
            this.value = value;
            this.type = type;
        }
       
        /**
         * Значение цены
         */
        public double value;
        /**
         * Тип цены: <br>0 - пункты <br>1 - рыночная цена
         */
        public int type;
    }
   
    //<editor-fold desc=" netbeansgenerated ">
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
                //System.out.println("name: " + info.getName());
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                MainForm frm = new MainForm();
                frm.setVisible(true);
                frm.setUserNameEditMode(false);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup bgTaskTime;
    private javax.swing.JButton btnCancelAccEdit;
    private javax.swing.JButton btnCloseStatistics;
    private javax.swing.JButton btnCreateTask;
    private javax.swing.JButton btnExitSettings;
    private javax.swing.ButtonGroup btnGroupCrazy;
    private javax.swing.JButton btnSaveAccData;
    private javax.swing.JCheckBox chkUseBreakeven;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel22;
    private javax.swing.JLabel jLabel23;
    private javax.swing.JLabel jLabel24;
    private javax.swing.JLabel jLabel25;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JLabel lblAccEdit;
    private javax.swing.JLabel lblAddOrder;
    private javax.swing.JLabel lblAddSmb;
    private javax.swing.JLabel lblClearOrders;
    private javax.swing.JLabel lblCreateTask;
    private javax.swing.JLabel lblCreateTaskAccCnt;
    private javax.swing.JLabel lblCurrentTime;
    private javax.swing.JLabel lblDeleteOrder;
    private javax.swing.JLabel lblDoModify;
    private javax.swing.JLabel lblGoNewOrder;
    private javax.swing.JLabel lblGoSettings;
    private javax.swing.JLabel lblGoTrading;
    public javax.swing.JLabel lblPkgCounter;
    private javax.swing.JLabel lblRemoveAccount;
    private javax.swing.JLabel lblSelectedUser;
    private javax.swing.JLabel lblStatBalance;
    private javax.swing.JLabel lblStatBalanceRUR;
    private javax.swing.JLabel lblStatBalanceUSD;
    private javax.swing.JLabel lblStatEquity;
    private javax.swing.JLabel lblStatOpenProfit;
    private javax.swing.JLabel lblStatProfitPerc;
    private javax.swing.JLabel lblStatProfitRUR;
    private javax.swing.JLabel lblStatProfitUSD;
    private javax.swing.JLabel lblStatistics;
    private javax.swing.JTable lstNewOrders;
    private javax.swing.JTable lstOrders;
    private javax.swing.JList lstSymbols;
    private javax.swing.JTable lstTaskList;
    public final javax.swing.JList lstUsers = new javax.swing.JList();
    private javax.swing.JMenuItem miEditAccount;
    private javax.swing.JMenuItem miShowStatistics;
    private javax.swing.JPopupMenu pmUsers;
    private javax.swing.JPanel pnlCreateTask;
    private javax.swing.JPanel pnlGenAction;
    private javax.swing.JPanel pnlGenList;
    private javax.swing.JPanel pnlGeneral;
    private javax.swing.JPanel pnlSettings;
    private javax.swing.JPanel pnlStatistics;
    private javax.swing.JPanel pnlToolTrading;
    private javax.swing.JPanel pnlTradeNewOrder;
    private javax.swing.JPanel pnlTradeTools;
    private javax.swing.JPanel pnlTrading;
    private javax.swing.JPanel pnlUserEditor;
    private javax.swing.JRadioButton rbCrazyAlt;
    private javax.swing.JRadioButton rbCrazyCtrl;
    private javax.swing.JRadioButton rbCrazyShift;
    private javax.swing.JRadioButton rbStartNow;
    private javax.swing.JRadioButton rbTimeStart;
    private javax.swing.JScrollPane spOrders;
    private javax.swing.JSpinner spnMaxTasks;
    private javax.swing.JSpinner spnOrderSendSeconds;
    private javax.swing.JPanel tbLogPane;
    private javax.swing.JTabbedPane tpSettings;
    private javax.swing.JTextField txtChangePrice;
    private javax.swing.JTextField txtChangeSL;
    private javax.swing.JTextField txtChangeTP;
    private javax.swing.JTextField txtChangeTrailing;
    private javax.swing.JTextField txtEURValue;
    public javax.swing.JTextArea txtLogText;
    private javax.swing.JTextField txtSybmolName;
    private javax.swing.JFormattedTextField txtTaskDate;
    private javax.swing.JTextField txtTaskName;
    private javax.swing.JFormattedTextField txtTaskTime;
    private javax.swing.JSpinner txtTraderComission;
    private javax.swing.JTextField txtUSDValue;
    private javax.swing.JTextField txtUserName;
    private javax.swing.JTextField txtUserNameEditor;
    // End of variables declaration//GEN-END:variables
    //</editor-fold>
}
TOP

Related Classes of psconsole.MainForm

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.