import { HubConnection, IStreamResult } from "@microsoft/signalr"

export class TestHub {
    constructor(private connection: HubConnection) {
    }

    getServerTime(): Promise<Date> {
        return this.connection.invoke('GetServerTime');
    }

    ping(message: string): Promise<Void> {
        return this.connection.invoke('Ping', message);
    }

    registerCallbacks(implementation: ITestHubCallbacks) {
        this.connection.on('Pong', (message) => implementation.pong(message));
        this.connection.on('OnClock', (dt) => implementation.onClock(dt));
    }

    unregisterCallbacks(implementation: ITestHubCallbacks) {
        this.connection.off('Pong', (message) => implementation.pong(message));
        this.connection.off('OnClock', (dt) => implementation.onClock(dt));
    }
}

export interface ITestHubCallbacks {
    pong(message: string): void;
    onClock(dt: Date): void;
}

export class MT4Hub {
    constructor(private connection: HubConnection) {
    }

    connect(args: ConnectArgs): Promise<boolean> {
        return this.connection.invoke('Connect', args);
    }

    subscribeToTicks(args: SubscribeToTicksArgs): Promise<void> {
        return this.connection.invoke('SubscribeToTicks', args);
    }

    subscribeToAllTicks(args: TradePlatformId): Promise<void> {
        return this.connection.invoke('SubscribeToAllTicks', args);
    }

    unsubscribeFromAllTicks(args: TradePlatformId): Promise<void> {
        return this.connection.invoke('UnsubscribeFromAllTicks', args);
    }

    unsubscribeFromTicks(args: SubscribeToTicksArgs): Promise<void> {
        return this.connection.invoke('UnsubscribeFromTicks', args);
    }

    subscribeToSymbols(args: TradePlatformId): Promise<void> {
        return this.connection.invoke('SubscribeToSymbols', args);
    }

    unsubscribeFromSymbols(args: TradePlatformId): Promise<void> {
        return this.connection.invoke('UnsubscribeFromSymbols', args);
    }

    subscribeToOnlineUpdates(args: TradePlatformId): Promise<void> {
        return this.connection.invoke('SubscribeToOnlineUpdates', args);
    }

    unsubscribeFromOnlineUpdates(args: TradePlatformId): Promise<void> {
        return this.connection.invoke('UnsubscribeFromOnlineUpdates', args);
    }

    streamTrades(args: TradePlatformId): IStreamResult<TradeExEventPayload> {
        return this.connection.stream('StreamTrades', args);
    }

    streamAllTicks(args: TradePlatformId): IStreamResult<SymbolInfo> {
        return this.connection.stream('StreamAllTicks', args);
    }

    streamMarginCallUpdates(args: TradePlatformId): IStreamResult<MarginLevel> {
        return this.connection.stream('StreamMarginCallUpdates', args);
    }

    streamUserUpdates(args: TradePlatformId): IStreamResult<UserUpdate> {
        return this.connection.stream('StreamUserUpdates', args);
    }

    registerCallbacks(implementation: IMT4HubCallbacks) {
        this.connection.on('OnMT4ConnectionStatus', (data) => implementation.onMT4ConnectionStatus(data));
        this.connection.on('OnTick', (data) => implementation.onTick(data));
        this.connection.on('OnTicks', (data) => implementation.onTicks(data));
        this.connection.on('OnTicksOHLC', (data) => implementation.onTicksOHLC(data));
        this.connection.on('OnMarginUpdate', (data) => implementation.onMarginUpdate(data));
        this.connection.on('OnSymbolUpdate', (data) => implementation.onSymbolUpdate(data));
        this.connection.on('OnOnlineUpdate', (data) => implementation.onOnlineUpdate(data));
        this.connection.on('OnDebug', (data) => implementation.onDebug(data));
    }

    unregisterCallbacks(implementation: IMT4HubCallbacks) {
        this.connection.off('OnMT4ConnectionStatus', (data) => implementation.onMT4ConnectionStatus(data));
        this.connection.off('OnTick', (data) => implementation.onTick(data));
        this.connection.off('OnTicks', (data) => implementation.onTicks(data));
        this.connection.off('OnTicksOHLC', (data) => implementation.onTicksOHLC(data));
        this.connection.off('OnMarginUpdate', (data) => implementation.onMarginUpdate(data));
        this.connection.off('OnSymbolUpdate', (data) => implementation.onSymbolUpdate(data));
        this.connection.off('OnOnlineUpdate', (data) => implementation.onOnlineUpdate(data));
        this.connection.off('OnDebug', (data) => implementation.onDebug(data));
    }
}

export interface IMT4HubCallbacks {
    onMT4ConnectionStatus(data: MT4ConnectionStatusArgs): void;
    onTick(data: TickArgs): void;
    onTicks(data: TicksArgs): void;
    onTicksOHLC(data: TicksOHLCArgs): void;
    onMarginUpdate(data: MarginUpdateArgs): void;
    onSymbolUpdate(data: SymbolUpdateArgs): void;
    onOnlineUpdate(data: OnlineUpdateArgs): void;
    onDebug(data: DebugArgs): void;
}

export class MT5Hub {
    constructor(private connection: HubConnection) {
    }

    connect(args: ConnectArgs2): Promise<boolean> {
        return this.connection.invoke('Connect', args);
    }

    subscribeToUsers(args: TradePlatformId): Promise<void> {
        return this.connection.invoke('SubscribeToUsers', args);
    }

    unsubscribeFromUsers(args: TradePlatformId): Promise<void> {
        return this.connection.invoke('UnsubscribeFromUsers', args);
    }

    subscribeToDeals(args: TradePlatformId): Promise<void> {
        return this.connection.invoke('SubscribeToDeals', args);
    }

    unsubscribeFromDeals(args: TradePlatformId): Promise<void> {
        return this.connection.invoke('UnsubscribeFromDeals', args);
    }

    subscribeToOrders(args: TradePlatformId): Promise<void> {
        return this.connection.invoke('SubscribeToOrders', args);
    }

    unsubscribeFromOrders(args: TradePlatformId): Promise<void> {
        return this.connection.invoke('UnsubscribeFromOrders', args);
    }

    subscribeToSymbols(args: TradePlatformId): Promise<void> {
        return this.connection.invoke('SubscribeToSymbols', args);
    }

    unsubscribeFromSymbols(args: TradePlatformId): Promise<void> {
        return this.connection.invoke('UnsubscribeFromSymbols', args);
    }

    subscribeToPositions(args: TradePlatformId): Promise<void> {
        return this.connection.invoke('SubscribeToPositions', args);
    }

    unsubscribeFromPositions(args: TradePlatformId): Promise<void> {
        return this.connection.invoke('UnsubscribeFromPositions', args);
    }

    subscribeToTicks(args: SubscribeToTicksArgs2): Promise<void> {
        return this.connection.invoke('SubscribeToTicks', args);
    }

    subscribeToAllTicks(args: TradePlatformId): Promise<void> {
        return this.connection.invoke('SubscribeToAllTicks', args);
    }

    unsubscribeFromAllTicks(args: TradePlatformId): Promise<void> {
        return this.connection.invoke('UnsubscribeFromAllTicks', args);
    }

    streamMarginCallUpdates(args: TradePlatformId): IStreamResult<MT5AccountMarginCallEventArgs> {
        return this.connection.stream('StreamMarginCallUpdates', args);
    }

    registerCallbacks(implementation: IMT5HubCallbacks) {
        this.connection.on('OnMT5ConnectionStatus', (data) => implementation.onMT5ConnectionStatus(data));
        this.connection.on('OnUser', (data) => implementation.onUser(data));
        this.connection.on('OnDeal', (data) => implementation.onDeal(data));
        this.connection.on('OnDealClean', (data) => implementation.onDealClean(data));
        this.connection.on('OnOrder', (data) => implementation.onOrder(data));
        this.connection.on('OnOrderClean', (data) => implementation.onOrderClean(data));
        this.connection.on('OnOrderSync', (data) => implementation.onOrderSync(data));
        this.connection.on('OnPosition', (data) => implementation.onPosition(data));
        this.connection.on('OnPositionClean', (data) => implementation.onPositionClean(data));
        this.connection.on('OnPositionSync', (data) => implementation.onPositionSync(data));
        this.connection.on('OnSymbol', (data) => implementation.onSymbol(data));
        this.connection.on('OnSymbolSync', (data) => implementation.onSymbolSync(data));
        this.connection.on('OnTick', (data) => implementation.onTick(data));
    }

    unregisterCallbacks(implementation: IMT5HubCallbacks) {
        this.connection.off('OnMT5ConnectionStatus', (data) => implementation.onMT5ConnectionStatus(data));
        this.connection.off('OnUser', (data) => implementation.onUser(data));
        this.connection.off('OnDeal', (data) => implementation.onDeal(data));
        this.connection.off('OnDealClean', (data) => implementation.onDealClean(data));
        this.connection.off('OnOrder', (data) => implementation.onOrder(data));
        this.connection.off('OnOrderClean', (data) => implementation.onOrderClean(data));
        this.connection.off('OnOrderSync', (data) => implementation.onOrderSync(data));
        this.connection.off('OnPosition', (data) => implementation.onPosition(data));
        this.connection.off('OnPositionClean', (data) => implementation.onPositionClean(data));
        this.connection.off('OnPositionSync', (data) => implementation.onPositionSync(data));
        this.connection.off('OnSymbol', (data) => implementation.onSymbol(data));
        this.connection.off('OnSymbolSync', (data) => implementation.onSymbolSync(data));
        this.connection.off('OnTick', (data) => implementation.onTick(data));
    }
}

export interface IMT5HubCallbacks {
    onMT5ConnectionStatus(data: MT5ConnectionStatusArgs): void;
    onUser(data: UserArgs): void;
    onDeal(data: DealArgs): void;
    onDealClean(data: DealCleanArgs): void;
    onOrder(data: OrderArgs): void;
    onOrderClean(data: OrderCleanArgs): void;
    onOrderSync(data: OrderSyncArgs): void;
    onPosition(data: PositionArgs): void;
    onPositionClean(data: PositionCleanArgs): void;
    onPositionSync(data: PositionSyncArgs): void;
    onSymbol(data: SymbolArgs): void;
    onSymbolSync(data: SymbolSyncArgs): void;
    onTick(data: TickArgs2): void;
}

export interface Void {
}

export interface ConnectArgs {
    tradePlatform: string;
    /** Timeout of pumping connection being UP and running. In milliseconds;
default = 30 seconds; */
    timeoutMs: number;
}

export interface SubscribeToTicksArgs {
    tradePlatform: string;
    symbol: string;
}

export interface TradePlatformId {
    tradePlatform: string;
}

export interface TradeExEventPayload extends TradeRecordDTO {
    /** add - order opened, delete - order closed, Update - IF login==0 THEN order deleted ELSE order updated */
    updateType: TransactionType;
}

export enum TransactionType {
    Add = "Add",
    Delete = "Delete",
    Update = "Update",
    ChangeGrp = "ChangeGrp",
}

export interface TradeRecordDTO {
    /** order ticket */
    order: number;
    /** owner's login */
    login: number;
    /** security precision */
    digits: number;
    /** it stores 100 times more volue than it is, for example value of 15 means 10/100=0.15 lots
             */
    volume: number;
    /** reserved */
    openPrice: number;
    sl: number;
    tp: number;
    gatewayVolume: number;
    commission: number;
    /** agent commission */
    commissionAgent: number;
    /** order swaps */
    storage: number;
    closePrice: number;
    profit: number;
    taxes: number;
    /** special value used by client experts */
    magic: number;
    /** trade order ticket on master server in STP */
    gatewayOrder: number;
    /** gateway order price deviation (pips) from order open price */
    gatewayOpenPrice: number;
    /** gateway order price deviation (pips) from order close price */
    gatewayClosePrice: number;
    /** margin convertation rate (rate of convertation from margin currency to deposit one)
             */
    marginRate: number;
    /** security */
    symbol: string;
    /** trade command (buy, sell, pending, balance, etc) */
    tradeCommand: TradeCommand;
    tradeRecordState: TradeRecordState;
    /** Volume in lots, for convenience */
    gatewayVolumeLots: number;
    tradeRecordReason: TradeRecordReason;
    /**   */
    convReserv: string;
    /** conversation rates from profit currency to group deposit currency
(first element-for open time, second element-for close time)
             */
    convRates: number[];
    comment: string;
    activationType: ActivationType;
    timeStamp: Date;
    /**   */
    apiData: number[];
    openTime: Date;
    closeTime: Date;
    /** pending order's expiration time */
    expiration: Date;
    /** Volume in lots, for convenience */
    volumeLots: number;
    /** add - order opened, delete - order closed, Update - IF login==0 THEN order deleted ELSE order updated */
    updateType: TransactionType;
}

export enum TradeCommand {
    Buy = "Buy",
    Sell = "Sell",
    BuyLimit = "BuyLimit",
    SellLimit = "SellLimit",
    BuyStop = "BuyStop",
    SellStop = "SellStop",
    Balance = "Balance",
    Credit = "Credit",
}

export enum TradeRecordState {
    OpenNormal = "OpenNormal",
    OpenRemand = "OpenRemand",
    OpenRestored = "OpenRestored",
    ClosedNormal = "ClosedNormal",
    ClosedPart = "ClosedPart",
    ClosedBy = "ClosedBy",
    Deleted = "Deleted",
}

export enum TradeRecordReason {
    Client = "Client",
    Expert = "Expert",
    Dealer = "Dealer",
    Signal = "Signal",
    Gateway = "Gateway",
    Mobile = "Mobile",
    Web = "Web",
    API = "API",
}

export enum ActivationType {
    None = "None",
    SL = "SL",
    TP = "TP",
    Pending = "Pending",
    Stopout = "Stopout",
    StopOutRollback = "StopOutRollback",
    PendingRollback = "PendingRollback",
    TPRollback = "TPRollback",
    SLRollback = "SLRollback",
}

export interface SymbolInfo {
    lastTime: Date | undefined;
    visible: boolean;
    symbol: string | undefined;
    digits: number;
    count: number;
    type: number;
    point: number;
    spread: number;
    spreadBalance: number;
    direction: SymbolPriceDirection;
    updateFlag: number;
    bid: number;
    ask: number;
    high: number;
    low: number;
    commission: number;
    commType: CommissionType;
}

export enum SymbolPriceDirection {
    Up = "Up",
    Down = "Down",
    None = "None",
}

export enum CommissionType {
    Money = "Money",
    Pips = "Pips",
    Percent = "Percent",
}

export interface MarginLevel {
    group: string | undefined;
    login: number;
    leverage: number;
    updated: number;
    balance: number;
    equity: number;
    volume: number;
    margin: number;
    free: number;
    level: number;
    controllingType: MarginControllingType;
    levelType: MarginLevelType;
}

export enum MarginControllingType {
    Percent = "Percent",
    Currency = "Currency",
}

export enum MarginLevelType {
    Ok = "Ok",
    MarginCall = "MarginCall",
    StopOut = "StopOut",
}

export interface UserUpdate {
    type: TransactionType;
    user: UserRecord;
}

export interface UserRecord {
    regDate: Date;
    lastDate: Date;
    timeStamp: Date;
    login: number;
    group: string | undefined;
    password: string | undefined;
    enable: number;
    enableChangePassword: number;
    enableReadOnly: number;
    enableOTP: number;
    enableReserved: number[] | undefined;
    passwordInvestor: string | undefined;
    passwordPhone: string | undefined;
    name: string | undefined;
    country: string | undefined;
    city: string | undefined;
    state: string | undefined;
    zipCode: string | undefined;
    address: string | undefined;
    leadSource: string | undefined;
    phone: string | undefined;
    email: string | undefined;
    comment: string | undefined;
    id: string | undefined;
    status: string | undefined;
    leverage: number;
    agentAccount: number;
    lastIP: number;
    balance: number;
    prevMonthBalance: number;
    prevBalance: number;
    credit: number;
    interestRate: number;
    taxes: number;
    prevMonthEquity: number;
    prevEquity: number;
    reserved2: number[] | undefined;
    otpSecret: string | undefined;
    secureReserved: string | undefined;
    sendReports: number;
    mqid: number;
    userColor: number;
    unused: string | undefined;
    apiData: string | undefined;
}

export interface MT4ConnectionStatusArgs extends TradePlatformId {
    connected: boolean;
}

export interface TickArgs extends TradePlatformId {
    tick: Tick;
}

export interface Tick {
    symbol: string;
    bid: number;
    ask: number;
    lastTime: Date | undefined;
}

export interface TicksArgs extends TradePlatformId {
    ticks: TickArgs[];
}

export interface TicksOHLCArgs extends TradePlatformId {
    ticks: OHLCS[];
}

export interface OHLCS {
    /** Priced being at the beginning of interval */
    open: BidAsk;
    /** highest ever bid and ask, calculated separately. */
    maximum: BidAsk;
    /** lowest ever bid and ask, calculated separately. */
    minimum: BidAsk;
    /** Priced being at the end of interval */
    close: BidAsk;
    symbol: string;
    lastTime: Date | undefined;
    /** number of ticks before groupping */
    volume: number;
}

export interface BidAsk {
    bid: number;
    ask: number;
}

export interface MarginUpdateArgs extends TradePlatformId {
    margins: MarginLevel[];
}

export interface SymbolUpdateArgs extends TradePlatformId {
    type: TransactionType;
    symbol: ConSymbol;
}

export interface ConSymbol {
    symbol: string | undefined;
    description: string | undefined;
    source: string | undefined;
    currency: string | undefined;
    type: number;
    digits: number;
    tradeMode: TradeMode;
    backgroundColor: number;
    count: number;
    countOriginal: number;
    realtime: number;
    starting: Date;
    expiration: Date;
    sessions: ConSessions[] | undefined;
    profitCalculationMode: ProfitCalculationMode;
    profitReserved: number;
    filter: number;
    filterCounter: number;
    filterLimit: number;
    filterSmoothing: number;
    filterReserved: number;
    logging: number;
    spread: number;
    spreadBalance: number;
    symbolExecMode: SymbolExecMode;
    swapEnable: number;
    swapType: SwapType;
    swapLong: number;
    swapShort: number;
    swapRollover3Days: number;
    contractSize: number;
    tickValue: number;
    tickSize: number;
    stopsLevel: number;
    gtcMode: GTCMode;
    marginCalculationMode: MarginCalculationMode;
    marginInitial: number;
    marginMaintenance: number;
    marginHedged: number;
    marginDivider: number;
    percentage: number;
    point: number;
    multiply: number;
    bidTickValue: number;
    askTickValue: number;
    longOnly: number;
    instantMaxVolume: number;
    marginCurrency: string | undefined;
    freezeLevel: number;
    marginHedgedStrong: number;
    valueDate: Date;
    quotesDelay: number;
    swapOpenPrice: number;
    swapVariationMargin: number;
}

export enum TradeMode {
    No = "No",
    Close = "Close",
    Full = "Full",
}

export interface ConSessions {
    quoteOvernight: number;
    tradeOvernight: number;
    quote: ConSession[] | undefined;
    trade: ConSession[] | undefined;
}

export interface ConSession {
    openHour: number;
    openMin: number;
    closeHour: number;
    closeMin: number;
    align: number[] | undefined;
}

export enum ProfitCalculationMode {
    Forex = "Forex",
    CFD = "CFD",
    Futures = "Futures",
}

export enum SymbolExecMode {
    Request = "Request",
    Instant = "Instant",
    Market = "Market",
}

export enum SwapType {
    Points = "Points",
    Dollars = "Dollars",
    Interest = "Interest",
    MarginCurrency = "MarginCurrency",
}

export enum GTCMode {
    Daily = "Daily",
    GTC = "GTC",
    DailyNoStops = "DailyNoStops",
}

export enum MarginCalculationMode {
    Forex = "Forex",
    CFD = "CFD",
    Futures = "Futures",
    CFDIndex = "CFDIndex",
    CFDLeverage = "CFDLeverage",
}

export interface OnlineUpdateArgs extends TradePlatformId {
    type: TransactionType;
    login: number;
}

export interface DebugArgs extends TradePlatformId {
    category: string;
    message: string;
    data: any;
}

export interface ConnectArgs2 extends TradePlatformId {
    /** Timeout of pumping connection being UP and running. In milliseconds;
default = 30 seconds; */
    timeoutMs: number;
}

export interface SubscribeToTicksArgs2 {
    tradePlatform: string;
    symbol: string;
}

export interface MT5AccountMarginCallEventArgs {
    account: MT5Account;
    type: MarginCallOrStopOut;
    direction: UpdateType;
}

export interface MT5Account {
    /** Get and set the login of the client, to whom the trading account belongs. */
    login: number;
    /** Get and set the number of decimal places in the account deposit currency. */
    currencyDigits: number | undefined;
    /** Get and set the balance of a trading account. */
    balance: number | undefined;
    /** Get and set the current amount of credit given to an account. */
    credit: number | undefined;
    /** Get and set the current value of the account margin. */
    margin: number | undefined;
    /** Get and set the free margin of an account. */
    marginFree: number | undefined;
    /** Get and set the margin level as a percentage. */
    marginLevel: number | undefined;
    /** Get and set the margin leverage. */
    marginLeverage: number | undefined;
    /** Get and set the size of the current profit for all open positions. */
    profit: number | undefined;
    /** Get and set the current size of swaps charged for open positions on the account. */
    storage: number | undefined;
    /** Get and set the size of floating profit/loss of open positions on the account. */
    floating: number | undefined;
    /** Get and set account equity. */
    equity: number | undefined;
    /** Get and set the account status as per the minimum amount of funds on the account required to maintain trading positions. */
    soActivation: SoActivation | undefined;
    /** Get and set the time when the Margin Call or Stop Out level was reached. */
    soTime: Date | undefined;
    /** Get and set the margin level of an account at the time of reaching the Stop Out level. */
    soLevel: number | undefined;
    /** Get and set the account equity at the time of reaching the Stop Out level. */
    soEquity: number | undefined;
    /** Get and set the margin amount on an account at the time of reaching the Stop Out level. */
    soMargin: number | undefined;
    /** Get and set the amount of the standard commission locked on the account, which has been accumulated during the day/month. */
    blockedCommission: number | undefined;
    /** Get and set the amount of intraday profit locked on the account. */
    blockedProfit: number | undefined;
    /** Get and set the current size of the initial margin of positions on a trading account. */
    marginInitial: number | undefined;
    /** Get and set the current size of the maintenance margin of positions on a trading account. */
    marginMaintenance: number | undefined;
    /** Get and set the current total amount of assets on a trading account. */
    assets: number | undefined;
    /** Get and set the current total amount of liabilities on a trading account. */
    liabilities: number | undefined;
}

export enum SoActivation {
    None = "None",
    MarginCall = "MarginCall",
    StopOut = "StopOut",
}

export enum MarginCallOrStopOut {
    MarginCall = "MarginCall",
    StopOut = "StopOut",
}

export enum UpdateType {
    Enter = "Enter",
    Leave = "Leave",
}

export interface MT5ConnectionStatusArgs extends TradePlatformId {
    connected: boolean;
}

export interface UserArgs extends TradePlatformId {
    user: MT5User;
    updateType: UpdateType2;
}

export interface MT5User {
    /** login */
    login: number | undefined;
    /** group */
    group: string;
    /** certificate serial number */
    certSerialNumber: number | undefined;
    /** UsersRights */
    rights: UsersRights | undefined;
    /** registration datetime (filled by MT5) */
    registration: Date | undefined;
    lastAccess: Date | undefined;
    /** Has No Setter In ManagerAPI, so all you can is to read this value. */
    lastIP: string | undefined;
    /** name */
    name: string | undefined;
    /** company */
    company: string | undefined;
    /** external system account (exchange, ECN, etc) */
    account: string | undefined;
    /** country */
    country: string | undefined;
    /** client language (WinAPI LANGID) */
    language: number | undefined;
    /** city */
    city: string | undefined;
    /** state */
    state: string | undefined;
    /** ZIP code */
    zipCode: string | undefined;
    address: string | undefined;
    phone: string | undefined;
    eMail: string | undefined;
    id: string | undefined;
    status: string | undefined;
    comment: string | undefined;
    color: number | undefined;
    phonePassword: string | undefined;
    leverage: number;
    agent: number | undefined;
    balance: number | undefined;
    credit: number | undefined;
    interestRate: number | undefined;
    commissionDaily: number | undefined;
    commissionMonthly: number | undefined;
    commissionAgentDaily: number | undefined;
    commissionAgentMonthly: number | undefined;
    balancePrevDay: number | undefined;
    balancePrevMonth: number | undefined;
    equityPrevDay: number | undefined;
    equityPrevMonth: number | undefined;
    lastPassChange: Date | undefined;
    mqid: string | undefined;
    leadCampaign: string | undefined;
    leadSource: string | undefined;
    clientID: number | undefined;
    firstName: string | undefined;
    lastName: string | undefined;
    middleName: string | undefined;
    otpSecret: string | undefined;
}

/** User rights Default = Enabled | Password | Trailing | Expert | Reports */
export enum UsersRights {
    None = "None",
    Enabled = "Enabled",
    Password = "Password",
    TradeDisabled = "TradeDisabled",
    Investor = "Investor",
    Confirmed = "Confirmed",
    Trailing = "Trailing",
    Expert = "Expert",
    Obsolete = "Obsolete",
    Reports = "Reports",
    Default = "Default",
    Readonly = "Readonly",
    ResetPass = "ResetPass",
    OTPEnabled = "OTPEnabled",
    UNKNOWN1000 = "UNKNOWN1000",
    SponsoredHosting = "SponsoredHosting",
    APIEnabled = "APIEnabled",
    PushNotification = "PushNotification",
    Technical = "Technical",
    ExcludeReports = "ExcludeReports",
    All = "All",
    UNKNOWN40000 = "UNKNOWN40000",
    UNKNOWN80000 = "UNKNOWN80000",
}

export enum UpdateType2 {
    Add = 0,
    Update = 1,
    Delete = 2,
    Archive = 3,
    Restore = 4,
}

export interface DealArgs extends TradePlatformId {
    deal: MT5Deal;
    updateType: UpdateType3;
}

export interface MT5Deal {
    /** deal ticket */
    deal: number;
    /** deal ticket in external system (exchange, ECN, etc) */
    externalID: string | undefined;
    /** client login */
    login: number | undefined;
    /** processed dealer login (0-means auto) */
    dealer: number | undefined;
    /** counterparty identification */
    partyID: number | undefined;
    /** deal order ticket */
    order: number | undefined;
    /** DealAction */
    action: DealAction | undefined;
    /** EntryFlags */
    entry: EntryFlag | undefined;
    /** price digits */
    digits: number | undefined;
    /** currency digits */
    digitsCurrency: number | undefined;
    /** symbol contract size */
    contractSize: number | undefined;
    /** deal creation datetime in seconds. If the value of this field is specified, the IMTDeal::TimeMsc value will be filled in automatically. */
    time: Date | undefined;
    /** deal symbol */
    symbol: string | undefined;
    /** deal price */
    price: number | undefined;
    /** order SL */
    priceSL: number | undefined;
    /** order TP */
    priceTP: number | undefined;
    /** deal volume */
    volume: number | undefined;
    /** deal volume with extended accuracy */
    volumeExt: number | undefined;
    /** closed volume */
    volumeClosed: number | undefined;
    /** closed volume with extended accuracy */
    volumeClosedExt: number | undefined;
    /** deal profit */
    profit: number | undefined;
    /** value */
    value: number | undefined;
    /** deal collected swaps */
    storage: number | undefined;
    /** deal commission */
    commission: number | undefined;
    /** obsolete value */
    obsoleteValue: number | undefined;
    /** fee */
    fee: number | undefined;
    /** profit conversion rate (from symbol profit currency to deposit currency) */
    rateProfit: number | undefined;
    /** margin conversion rate (from symbol margin currency to deposit currency) */
    rateMargin: number | undefined;
    /** expert id (filled by expert advisor) */
    expertID: number | undefined;
    /** position id */
    positionID: number | undefined;
    /** deal comment */
    comment: string | undefined;
    /** deal profit in symbol's profit currency */
    profitRaw: number | undefined;
    /** closed position  price */
    pricePosition: number | undefined;
    /** tick value */
    tickValue: number | undefined;
    /** tick size */
    tickSize: number | undefined;
    /** flags */
    flags: number | undefined;
    /** deal creation datetime in msc since 1970.01.01. If the value of this field is specified, the IMTDeal::Time value will be filled in automatically */
    timeMsc: Date | undefined;
    /** DealReason */
    reason: DealReason | undefined;
    /** source gateway name */
    gateway: string | undefined;
    /** deal price on gateway */
    priceGateway: number | undefined;
    /** Has No Setter In ManagerAPI, so all you can is to read this value.
Get the market Bid price as at the time of deal execution by the server */
    marketBid: number | undefined;
    /** Has No Setter In ManagerAPI, so all you can is to read this value.
Get the market Ask price as at the time of deal execution by the server */
    marketAsk: number | undefined;
    /** Has No Setter In ManagerAPI, so all you can is to read this value.
Get the market Last price as at the time of deal execution by the server */
    marketLast: number | undefined;
    /** Has No Setter In ManagerAPI, so all you can is to read this value.
modification flags */
    modificationFlags: TradeModifyFlags | undefined;
}

export enum DealAction {
    Buy = "Buy",
    Sell = "Sell",
    Balance = "Balance",
    Credit = "Credit",
    Charge = "Charge",
    Correction = "Correction",
    Bonus = "Bonus",
    Commission = "Commission",
    CommissionDaily = "CommissionDaily",
    CommissionMonthly = "CommissionMonthly",
    AgentDaily = "AgentDaily",
    AgentMonthly = "AgentMonthly",
    InterestRate = "InterestRate",
    BuyCanceled = "BuyCanceled",
    SellCanceled = "SellCanceled",
    Dividend = "Dividend",
    DividendFranked = "DividendFranked",
    Tax = "Tax",
    Agent = "Agent",
    SOCompensation = "SOCompensation",
    SOCompensationCredit = "SOCompensationCredit",
}

export enum EntryFlag {
    In = "In",
    Out = "Out",
    InOut = "InOut",
    OutBy = "OutBy",
}

export enum DealReason {
    Client = "Client",
    Expert = "Expert",
    Dealer = "Dealer",
    Sl = "Sl",
    Tp = "Tp",
    So = "So",
    Rollover = "Rollover",
    ExternalClient = "ExternalClient",
    VMargin = "VMargin",
    Gateway = "Gateway",
    Signal = "Signal",
    Settlement = "Settlement",
    Transfer = "Transfer",
    Sync = "Sync",
    ExternalService = "ExternalService",
    Migration = "Migration",
    Mobile = "Mobile",
    Web = "Web",
    Split = "Split",
    CorporateAction = "CorporateAction",
}

/** also used for Deal,Order,Position */
export enum TradeModifyFlags {
    None = "None",
    Admin = "Admin",
    Manager = "Manager",
    Position = "Position",
    Restore = "Restore",
    ApiAdmin = "ApiAdmin",
    ApiManager = "ApiManager",
    ApiServer = "ApiServer",
    ApiGateway = "ApiGateway",
    All = "All",
}

export enum UpdateType3 {
    Add = 0,
    Update = 1,
    Delete = 2,
}

export interface DealCleanArgs extends TradePlatformId {
    login: number;
}

export interface OrderArgs extends TradePlatformId {
    order: MT5Order;
    updateType: UpdateType4;
}

export interface MT5Order {
    /** order ticket */
    order: number | undefined;
    /** order ticket in external system (exchange, ECN, etc) */
    externalID: string | undefined;
    /** client login */
    login: number | undefined;
    /** processed dealer login (0-means auto) */
    dealer: number | undefined;
    /** counterparty identification */
    partyID: number | undefined;
    /** order symbol */
    symbol: string | undefined;
    /** price digits */
    digits: number | undefined;
    /** currency digits */
    digitsCurrency: number | undefined;
    /** contract size */
    contractSize: number | undefined;
    /** OrderState */
    state: OrderState | undefined;
    /** OrderReason */
    reason: OrderReason | undefined;
    /** order setup time */
    timeSetup: Date | undefined;
    /** order expiration */
    timeExpiration: Date | undefined;
    /** order filling/cancel time */
    timeDone: Date | undefined;
    /** OrderType */
    type: OrderType | undefined;
    /** OrderFilling */
    typeFill: OrderFilling | undefined;
    /** OrderTime */
    typeTime: OrderTime | undefined;
    /** order price */
    priceOrder: number | undefined;
    /** order trigger price (stop-limit price) */
    priceTrigger: number | undefined;
    /** order current price */
    priceCurrent: number | undefined;
    /** order SL */
    priceSL: number | undefined;
    /** order TP */
    priceTP: number | undefined;
    /** order initial volume */
    volumeInitial: number | undefined;
    /** order current volume */
    volumeCurrent: number | undefined;
    /** expert id (filled by expert advisor) */
    expertID: number | undefined;
    /** position id */
    positionID: number | undefined;
    /** order comment */
    comment: string | undefined;
    /** Has No Setter In ManagerAPI, so all you can is to read this value.
order activation state, time and price */
    activationMode: number | undefined;
    /** Has No Setter In ManagerAPI, so all you can is to read this value. */
    activationTime: Date | undefined;
    /** Has No Setter In ManagerAPI, so all you can is to read this value.
Gets the price, at which the order was activated */
    activationPrice: number | undefined;
    /** Has No Setter In ManagerAPI, so all you can is to read this value. */
    activationFlags: TradeActivationFlags | undefined;
    /** Gets and sets the order placing time in milliseconds, since 1970.01.01
If the value of this field is specified, the TimeSetup value will be filled in automatically. */
    timeSetupMsc: Date | undefined;
    /** Gets and sets the order execution time in milliseconds, since 1970.01.01
If the value of this field is specified, the TimeDone value will be filled in automatically. */
    timeDoneMsc: Date | undefined;
    /** margin conversion rate (from symbol margin currency to deposit currency) */
    rateMargin: number | undefined;
    /** position by id */
    positionByID: number | undefined;
    /** modification flags */
    modificationFlags: number | undefined;
    /** order initial volume with extended accuracy */
    volumeInitialExt: number | undefined;
    /** order current volume with extended accuracy */
    volumeCurrentExt: number | undefined;
}

export enum OrderState {
    Started = 0,
    Placed = 1,
    Canceled = 2,
    Partial = 3,
    Filled = 4,
    Rejected = 5,
    Expired = 6,
    RequestAdd = 7,
    RequestModify = 8,
    RequestCancel = 9,
}

export enum OrderReason {
    Client = 0,
    Expert = 1,
    Dealer = 2,
    SL = 3,
    TP = 4,
    SO = 5,
    Rollover = 6,
    ExternalClient = 7,
    VMargin = 8,
    Gateway = 9,
    Signal = 10,
    Settlement = 11,
    Transfer = 12,
    Sync = 13,
    ExternalService = 14,
    Migration = 15,
    Mobile = 16,
    Web = 17,
    Split = 18,
    CorporateAction = 19,
}

export enum OrderType {
    Buy = "Buy",
    Sell = "Sell",
    BuyLimit = "BuyLimit",
    SellLimit = "SellLimit",
    BuyStop = "BuyStop",
    SellStop = "SellStop",
    BuyStopLimit = "BuyStopLimit",
    SellStopLimit = "SellStopLimit",
    CloseBy = "CloseBy",
}

export enum OrderFilling {
    FoK = "FoK",
    IoC = "IoC",
    Return = "Return",
    BoC = "BoC",
}

export enum OrderTime {
    GtC = "GtC",
    Day = "Day",
    Specified = "Specified",
    SpecifiedDay = "SpecifiedDay",
}

export enum TradeActivationFlags {
    None = "None",
    NoLimit = "NoLimit",
    NoStop = "NoStop",
    NoSLimit = "NoSLimit",
    NoSL = "NoSL",
    NoTP = "NoTP",
    NoSO = "NoSO",
    NoExpiration = "NoExpiration",
    All = "All",
}

export enum UpdateType4 {
    Add = 0,
    Update = 1,
    Delete = 2,
}

export interface OrderCleanArgs extends TradePlatformId {
    login: number;
}

export interface OrderSyncArgs extends TradePlatformId {
}

export interface PositionArgs extends TradePlatformId {
    position: MT5Position;
    updateType: UpdateType5;
}

export interface MT5Position {
    /** Gets the login of the client, to whom the trade position belongs */
    login: number | undefined;
    /** position symbol */
    symbol: string | undefined;
    /** PositionAction */
    action: PositionActions | undefined;
    /** price digits */
    digits: number | undefined;
    /** currency digits */
    digitsCurrency: number | undefined;
    /** symbol contract size */
    contractSize: number | undefined;
    /** position ticket */
    position: number | undefined;
    /** The ticket of a position in an external trading system */
    externalId: string | undefined;
    /** position create time */
    timeCreate: Date | undefined;
    /** position last update time */
    timeUpdate: Date | undefined;
    /** position create time in msc since 1970.01.01
If the value of this field is specified, the TimeCreate value will be filled in automatically. */
    timeCreateMsc: Date | undefined;
    /** position last update time in msc since 1970.01.01
If the value of this field is specified, the TimeUpdate value will be filled in automatically. */
    timeUpdateMsc: Date | undefined;
    /** position weighted average open price */
    priceOpen: number | undefined;
    /** position current price */
    priceCurrent: number | undefined;
    /** position SL price */
    priceSL: number | undefined;
    /** position TP price */
    priceTP: number | undefined;
    /** position volume */
    volume: number | undefined;
    /** position volume */
    volumeExt: number | undefined;
    /** position floating profit */
    profit: number | undefined;
    /** position accumulated swaps */
    storage: number | undefined;
    /** profit conversion rate (from symbol profit currency to deposit currency) */
    rateProfit: number | undefined;
    /** margin conversion rate (from symbol margin currency to deposit currency) */
    rateMargin: number | undefined;
    /** expert id (filled by expert advisor) */
    expertId: number | undefined;
    /** expert position id */
    expertPositionId: number | undefined;
    /**   */
    comment: string | undefined;
    /** The login of a dealer, who has processed the order that opened the position. 0 means that the order was processed automatically by the server */
    dealer: number | undefined;
    /** order activation state, time and price */
    activationMode: ActivationModes | undefined;
    activationTime: Date | undefined;
    activationPrice: number | undefined;
    activationFlags: TradeActivationFlags | undefined;
    /** modification flags */
    modificationFlags: TradeModifyFlags | undefined;
    /** position reason - PositionReason */
    reason: PositionReasons | undefined;
}

/** PositionReason */
export enum PositionActions {
    Buy = "Buy",
    Sell = "Sell",
}

export enum ActivationModes {
    None = "None",
    SL = "SL",
    TP = "TP",
    StopOut = "StopOut",
}

export enum PositionReasons {
    Client = "Client",
    Expert = "Expert",
    Dealer = "Dealer",
    SL = "SL",
    TP = "TP",
    SO = "SO",
    Rollover = "Rollover",
    ExternalClient = "ExternalClient",
    VMargin = "VMargin",
    Gateway = "Gateway",
    Signal = "Signal",
    Settlement = "Settlement",
    Transfer = "Transfer",
    Sync = "Sync",
    ExternalService = "ExternalService",
    Migration = "Migration",
    Mobile = "Mobile",
    Web = "Web",
    Split = "Split",
    CorporateAction = "CorporateAction",
}

export enum UpdateType5 {
    Add = 0,
    Update = 1,
    Delete = 2,
}

export interface PositionCleanArgs extends TradePlatformId {
    login: number;
}

export interface PositionSyncArgs extends TradePlatformId {
}

export interface SymbolArgs extends TradePlatformId {
    symbol: MT5Symbol;
    updateType: UpdateType6;
}

export interface MT5Symbol {
    /** name */
    symbol: string | undefined;
    /** hierarchical symbol path (including symbol name) */
    path: string | undefined;
    /** ISIN */
    isin: string | undefined;
    /** local description */
    description: string | undefined;
    /** internation description */
    international: string | undefined;
    /** basic symbol name */
    basis: string | undefined;
    /** source symbol name */
    source: string | undefined;
    /** symbol specification page URL */
    page: string | undefined;
    /** symbol base currency */
    currencyBase: string | undefined;
    /** Has No Setter In ManagerAPI, so all you can is to read this value. */
    currencyBaseDigits: number | undefined;
    /** symbol profit currency */
    currencyProfit: string | undefined;
    /** Has No Setter In ManagerAPI, so all you can is to read this value. */
    currencyProfitDigits: number | undefined;
    /** symbol margin currency */
    currencyMargin: string | undefined;
    /** Has No Setter In ManagerAPI, so all you can is to read this value. */
    currencyMarginDigits: number | undefined;
    /** symbol color */
    color: number | undefined;
    /** symbol background color */
    colorBackground: number | undefined;
    /** symbol digits */
    digits: number | undefined;
    point: number | undefined;
    /** Has No Setter In ManagerAPI, so all you can is to read this value. */
    multiply: number | undefined;
    /** EnTickFlags */
    tickFlags: EnTickFlags | undefined;
    /** Depth of Market depth (both legs) */
    tickBookDepth: number | undefined;
    /** filtration soft level */
    filterSoft: number | undefined;
    /** filtration soft level counter */
    filterSoftTicks: number | undefined;
    /** filtration hard level */
    filterHard: number | undefined;
    /** filtration hard level counter */
    filterHardTicks: number | undefined;
    /** filtration discard level */
    filterDiscard: number | undefined;
    /** spread max value */
    filterSpreadMax: number | undefined;
    /** spread min value */
    filterSpreadMin: number | undefined;
    /** EnTradeMode */
    tradeMode: EnTradeMode | undefined;
    /** EnCalcMode */
    calcMode: EnCalcMode | undefined;
    /** EnExecutionMode */
    execMode: EnExecutionMode | undefined;
    /** EnGTCMode */
    gtcMode: EnGtcMode | undefined;
    /** EnFillingFlags */
    fillFlags: EnFillingFlags | undefined;
    /** EnExpirationFlags */
    expirFlags: EnExpirationFlags | undefined;
    /** symbol spread (0-floating) */
    spread: number | undefined;
    /** spread balance */
    spreadBalance: number | undefined;
    /** spread difference */
    spreadDiff: number | undefined;
    /** spread difference balance */
    spreadDiffBalance: number | undefined;
    /** tick value */
    tickValue: number | undefined;
    /** tick size */
    tickSize: number | undefined;
    /** contract size */
    contractSize: number | undefined;
    /** stops level */
    stopsLevel: number | undefined;
    /** freeze level */
    freezeLevel: number | undefined;
    /** The time to wait for quotes in seconds, after which trading is automatically disabled for the symbol. */
    quotesTimeout: number | undefined;
    /** minimal volume */
    volumeMin: number | undefined;
    /** maximal volume */
    volumeMax: number | undefined;
    /** volume step */
    volumeStep: number | undefined;
    /** cumulative positions and orders limit */
    volumeLimit: number | undefined;
    /** EnMarginFlags */
    marginFlags: EnMarginFlags | undefined;
    /** initial margin */
    marginInitial: number | undefined;
    /** maintenance margin */
    marginMaintenance: number | undefined;
    /** long orders and positions margin rate */
    marginLong: number | undefined;
    /** short orders and positions margin rate */
    marginShort: number | undefined;
    /** limit orders and positions margin rate */
    marginLimit: number | undefined;
    /** stop orders and positions margin rate */
    marginStop: number | undefined;
    /** stop-limit orders and positions margin rate */
    marginStopLimit: number | undefined;
    /** EnSwapMode */
    swapMode: EnSwapMode | undefined;
    /** long positions swaps rate */
    swapLong: number | undefined;
    /** short positions swaps rate */
    swapShort: number | undefined;
    /** 3 time swaps day, EnSwapDay */
    swap3Day: EnSwapDays | undefined;
    /** trade start date */
    timeStart: Date | undefined;
    /** The date of trading expiration for a symbol.
It is considered that there is no time limitation for trading by a symbol if both IMTConSymbol::TimeStart and IMTConSymbol::TimeExpiration are equal to 0. */
    timeExpiration: Date | undefined;
    /** Not yet implemented. Contact us for further information
Update a quoting session of a symbol by the day and index. The day is specified by a value 0 (Sunday) to 6 (Saturday). */
    sessionQuote: MT5SymbolSession[][] | undefined;
    /** Not yet implemented. Contact us for further information */
    sessionTrade: MT5SymbolSession[][] | undefined;
    /** request execution flags */
    reFlags: EnRequestFlags | undefined;
    /** Time in seconds during which the price issued by a dealer in the request execution mode is valid. */
    reTimeout: number | undefined;
    /** instant execution check mode */
    ieCheckMode: EnInstantMode | undefined;
    /** Get and set the maximum allowed difference between the time of arrival of the price, at which the client places an order, and the time of the last price. */
    ieTimeout: number | undefined;
    /** instant execution profit slippage */
    ieSlipProfit: number | undefined;
    /** instant execution losing slippage */
    ieSlipLosing: number | undefined;
    /** instant execution max volume */
    ieVolumeMax: number | undefined;
    /** settle price (for futures) */
    priceSettle: number | undefined;
    /** price limit max (for futures) */
    priceLimitMax: number | undefined;
    /** price limit min (for futures) */
    priceLimitMin: number | undefined;
    /** EnTradeFlags */
    tradeFlags: EnTradeFlags | undefined;
    /** EnOrderFlags */
    orderFlags: EnOrderFlags | undefined;
    /** orders and positions margin rates */
    marginRateInitial: { [key in keyof typeof EnMarginRateTypes]?: number; } | undefined;
    /** orders and positions margin rates */
    marginRateMaintenance: { [key in keyof typeof EnMarginRateTypes]?: number; } | undefined;
    /** options mode EnOptionMode */
    optionsMode: EnOptionMode | undefined;
    /** option strike price value */
    priceStrike: number | undefined;
    /** liquidity rate */
    marginRateLiquidity: number | undefined;
    /** bond face value */
    faceValue: number | undefined;
    /** bond accrued interest */
    accruedInterest: number | undefined;
    /** futures splice type EnSpliceType */
    spliceType: EnSpliceType | undefined;
    /** futures splice time type EnSpliceType */
    spliceTimeType: EnSpliceTimeType | undefined;
    /** The splicing shift as a number of days to the past from the symbol's expiration date IMTConSymbol::TimeExpiration */
    spliceTimeDays: number | undefined;
    /** hedged positions margin rate */
    marginHedged: number | undefined;
    /** currency rate */
    marginRateCurrency: number | undefined;
    /** gap level */
    filterGap: number | undefined;
    /** gap level ticks */
    filterGapTicks: number | undefined;
    /** chart mode */
    chartMode: EnChartMode | undefined;
    /** instant execution flags with extended accuracy */
    ieFlags: EnInstantFlags | undefined;
    /** minimal volume with extended accuracy */
    volumeMinExt: number | undefined;
    /** maximal volume with extended accuracy */
    volumeMaxExt: number | undefined;
    /** volume step with extended accuracy */
    volumeStepExt: number | undefined;
    /** cumulative positions and orders limit with extended accuracy */
    volumeLimitExt: number | undefined;
    /** instant execution max volume with extended accuracy */
    ieVolumeMaxExt: number | undefined;
    /** category */
    category: string | undefined;
    /** exchange */
    exchange: string | undefined;
    /** CFI */
    cfi: string | undefined;
    /** Sector */
    sector: EnSectors | undefined;
    /** Industry */
    industry: EnIndustries | undefined;
    /** Country - ISO 3166-1 alpha-3 code */
    country: string | undefined;
    /** Delay for subscriptions */
    subscriptionsDelay: number | undefined;
    /** Days in year */
    swapYearDays: number | undefined;
    /** swap flags */
    swapFlags: EnSwapFlags | undefined;
    /** swap rate for Sunday */
    swapRateSunday: number | undefined;
    /** swap rate for Monday */
    swapRateMonday: number | undefined;
    /** swap rate for Tuesday */
    swapRateTuesday: number | undefined;
    /** swap rate for Wednesday */
    swapRateWednesday: number | undefined;
    /** swap rate for Thursday */
    swapRateThursday: number | undefined;
    /** swap rate for Friday */
    swapRateFriday: number | undefined;
    /** swap rate for Saturday */
    swapRateSaturday: number | undefined;
}

export enum EnTickFlags {
    None = 0,
    Realtime = 1,
    CollectRaw = 2,
    FeedStats = 4,
    NegativePrices = 8,
    All = 15,
}

export enum EnTradeMode {
    Disabled = 0,
    LongOnly = 1,
    ShortOnly = 2,
    CloseOnly = 3,
    Full = 4,
}

export enum EnCalcMode {
    Forex = 0,
    Futures = 1,
    Cfd = 2,
    CfdIndex = 3,
    CfdLeverage = 4,
    ForexNoLeverage = 5,
    ExchStocks = 32,
    ExchFutures = 33,
    ExchFuturesForts = 34,
    ExchOptions = 35,
    ExchOptionsMargin = 36,
    ExchBonds = 37,
    ExchStocksMoex = 38,
    ExchBondsMoex = 39,
    ServCollateral = 64,
}

export enum EnExecutionMode {
    Request = 0,
    Instant = 1,
    Market = 2,
    Exchange = 3,
}

export enum EnGtcMode {
    GtC = 0,
    Daily = 1,
    DailyNoStops = 2,
}

export enum EnFillingFlags {
    None = "None",
    FoK = "FoK",
    IoC = "IoC",
    BoC = "BoC",
    All = "All",
}

export enum EnExpirationFlags {
    None = 0,
    GtC = 1,
    Day = 2,
    Specified = 4,
    SpecifiedDay = 8,
    All = 15,
}

export enum EnMarginFlags {
    None = 0,
    CheckProcess = 1,
    CheckSLTP = 2,
    HedgeLargeLeg = 4,
    ExcludePl = 8,
    All = 15,
    RecalcRates = 16,
}

export enum EnSwapMode {
    Disabled = 0,
    ByPoints = 1,
    BySymbolCurrency = 2,
    ByMarginCurrency = 3,
    ByGroupCurrency = 4,
    ByInterestCurrent = 5,
    ByInterestOpen = 6,
    ReopenByClosePrice = 7,
    ReopenByBid = 8,
    ByProfitCurrency = 9,
}

export enum EnSwapDays {
    Sunday = 0,
    Monday = 1,
    Tuesday = 2,
    Wednesday = 3,
    Thursday = 4,
    Friday = 5,
    Saturday = 6,
    Disabled = 7,
}

export interface MT5SymbolSession {
    /** The session opening time in minutes from 00:00. For example, 100 denotes 01:40. */
    open: number | undefined;
    /** Get the number of hours in the opening time of trading or quoting session of a symbol. */
    openHours: number | undefined;
    /** The number of minutes in the opening time of trading or quoting session of a symbol. */
    openMinutes: number | undefined;
    /** The session closing time in minutes from 00:00. For example, 100 denotes 01:40. */
    close: number | undefined;
    /** The number of hours in the closing time of trading or quoting session of a symbol. */
    closeHours: number | undefined;
    /** The number of minutes in the closing time of trading or quoting session of a symbol. */
    closeMinutes: number | undefined;
}

export enum EnRequestFlags {
    None = 0,
    Order = 1,
    All = 1,
}

/** Данное перечисление используется в следующих методах: IMTConSymbol::IECheckMode IMTConGroupSymbol::IECheckMode IMTConGroupSymbol::IECheckModeDefault */
export enum EnInstantMode {
    Normal = 0,
}

/** Common Trade Flags */
export enum EnTradeFlags {
    None = 0,
    ProfitByMarket = 1,
    AllowSignals = 2,
    Default = 2,
    TradeFlagsAll = 3,
}

export enum EnOrderFlags {
    None = 0,
    Market = 1,
    Limit = 2,
    Stop = 4,
    StopLimit = 8,
    SL = 16,
    TP = 32,
    CloseBy = 64,
    All = 127,
}

/** Данное перечисление используется в следующих методах: IMTConSymbol::MarginRateInitial IMTConSymbol::MarginRateMaintenance IMTConGroupSymbol::MarginRateInitial IMTConGroupSymbol::MarginRateInitialDefault IMTConGroupSymbol::MarginRateMaintenance IMTConGroupSymbol::MarginRateMaintenanceDefault */
export enum EnMarginRateTypes {
    Buy = 0,
    Sell = 1,
    BuyLimit = 2,
    SellLimit = 3,
    BuyStop = 4,
    SellStop = 5,
    BuyStopLimit = 6,
    SellStopLimit = 7,
}

export enum EnOptionMode {
    EuropeanCall = 0,
    EuropeanPut = 1,
    AmericanCall = 2,
    AmericanPut = 3,
}

export enum EnSpliceType {
    None = 0,
    Unadjusted = 1,
    Adjusted = 2,
}

export enum EnSpliceTimeType {
    Expiration = 0,
}

export enum EnChartMode {
    BidPrice = 0,
    LastPrice = 1,
    Old = 255,
}

export enum EnInstantFlags {
    None = 0,
    FastConfirmation = 1,
    All = 1,
}

export enum EnSectors {
    Undefined = "Undefined",
    BasicMaterials = "BasicMaterials",
    CommunicationServices = "CommunicationServices",
    ConsumerCyclical = "ConsumerCyclical",
    ConsumerDefensive = "ConsumerDefensive",
    Energy = "Energy",
    Financial = "Financial",
    Healthcare = "Healthcare",
    Industrials = "Industrials",
    RealEstate = "RealEstate",
    Technology = "Technology",
    Utilities = "Utilities",
    Currency = "Currency",
    CurrencyCrypto = "CurrencyCrypto",
    Indexes = "Indexes",
    Commodities = "Commodities",
}

export enum EnIndustries {
    Undefined = "Undefined",
    AgriculturalInputs = "AgriculturalInputs",
    Aluminium = "Aluminium",
    BuildingMaterials = "BuildingMaterials",
    Chemicals = "Chemicals",
    CokingCoal = "CokingCoal",
    Copper = "Copper",
    Gold = "Gold",
    LumberWood = "LumberWood",
    IndustrialMetals = "IndustrialMetals",
    PreciousMetals = "PreciousMetals",
    Paper = "Paper",
    Silver = "Silver",
    SpecialtyChemicals = "SpecialtyChemicals",
    Steel = "Steel",
    BasicMaterialsEnd = "BasicMaterialsEnd",
    Advertising = "Advertising",
    Broadcasting = "Broadcasting",
    GamingMultimedia = "GamingMultimedia",
    Entertainment = "Entertainment",
    InternetContent = "InternetContent",
    Publishing = "Publishing",
    Telecom = "Telecom",
    CommunicationEnd = "CommunicationEnd",
    ApparelManufacturing = "ApparelManufacturing",
    ApparelRetail = "ApparelRetail",
    AutoManufacturers = "AutoManufacturers",
    AutoParts = "AutoParts",
    AutoDealership = "AutoDealership",
    DepartmentStores = "DepartmentStores",
    FootwearAccessories = "FootwearAccessories",
    Furnishings = "Furnishings",
    Gambling = "Gambling",
    HomeImprovRetail = "HomeImprovRetail",
    InternetRetail = "InternetRetail",
    Leisure = "Leisure",
    Lodging = "Lodging",
    LuxuryGoods = "LuxuryGoods",
    PackagingContainers = "PackagingContainers",
    PersonalServices = "PersonalServices",
    RecreationalVehicles = "RecreationalVehicles",
    ResidentConstruction = "ResidentConstruction",
    ResortsCasinos = "ResortsCasinos",
    Restaurants = "Restaurants",
    SpecialtyRetail = "SpecialtyRetail",
    TextileManufacturing = "TextileManufacturing",
    TravelServices = "TravelServices",
    ConsumerCyclEnd = "ConsumerCyclEnd",
    BeveragesBrewers = "BeveragesBrewers",
    BeveragesNonAlco = "BeveragesNonAlco",
    BeveragesWineries = "BeveragesWineries",
    Confectioners = "Confectioners",
    DiscountStores = "DiscountStores",
    EducationTrainig = "EducationTrainig",
    FarmProducts = "FarmProducts",
    FoodDistribution = "FoodDistribution",
    GroceryStores = "GroceryStores",
    HouseholdProducts = "HouseholdProducts",
    PackagedFoods = "PackagedFoods",
    Tobacco = "Tobacco",
    ConsumerDefEnd = "ConsumerDefEnd",
    OilGasDrilling = "OilGasDrilling",
    OilGasEp = "OilGasEp",
    OilGasEquipment = "OilGasEquipment",
    OilGasIntegrated = "OilGasIntegrated",
    OilGasMidstream = "OilGasMidstream",
    OilGasRefining = "OilGasRefining",
    ThermalCoal = "ThermalCoal",
    Uranium = "Uranium",
    EnergyEnd = "EnergyEnd",
    ExchangeTradedFund = "ExchangeTradedFund",
    AssetsManagement = "AssetsManagement",
    BanksDiversified = "BanksDiversified",
    BanksRegional = "BanksRegional",
    CapitalMarkets = "CapitalMarkets",
    CloseEndFundDebt = "CloseEndFundDebt",
    CloseEndFundEquity = "CloseEndFundEquity",
    CloseEndFundForeign = "CloseEndFundForeign",
    CreditServices = "CreditServices",
    FinancialConglomerate = "FinancialConglomerate",
    FinancialDataExchange = "FinancialDataExchange",
    InsuranceBrokers = "InsuranceBrokers",
    InsuranceDiversified = "InsuranceDiversified",
    InsuranceLife = "InsuranceLife",
    InsuranceProperty = "InsuranceProperty",
    InsuranceReinsurance = "InsuranceReinsurance",
    InsuranceSpecialty = "InsuranceSpecialty",
    MortgageFinance = "MortgageFinance",
    ShellCompanies = "ShellCompanies",
    FinancialEnd = "FinancialEnd",
    Biotechnology = "Biotechnology",
    DiagnosticsResearch = "DiagnosticsResearch",
    DrugsManufacturers = "DrugsManufacturers",
    DrugsManufacturersSpec = "DrugsManufacturersSpec",
    HealthcarePlans = "HealthcarePlans",
    HealthInformation = "HealthInformation",
    MedicalFacilities = "MedicalFacilities",
    MedicalDevices = "MedicalDevices",
    MedicalDistribution = "MedicalDistribution",
    MedicalInstruments = "MedicalInstruments",
    PharmRetailers = "PharmRetailers",
    HealthcareEnd = "HealthcareEnd",
    AerospaceDefense = "AerospaceDefense",
    Airlines = "Airlines",
    AirportsServices = "AirportsServices",
    BuildingProducts = "BuildingProducts",
    BusinessEquipment = "BusinessEquipment",
    Conglomerates = "Conglomerates",
    ConsultingServices = "ConsultingServices",
    ElectricalEquipment = "ElectricalEquipment",
    EngineeringConstruction = "EngineeringConstruction",
    FarmHeavyMachinery = "FarmHeavyMachinery",
    IndustrialDistribution = "IndustrialDistribution",
    InfrastructureOperations = "InfrastructureOperations",
    FreightLogistics = "FreightLogistics",
    MarineShipping = "MarineShipping",
    MetalFabrication = "MetalFabrication",
    PollutionControl = "PollutionControl",
    Railroads = "Railroads",
    RentalLeasing = "RentalLeasing",
    SecurityProtection = "SecurityProtection",
    SpealityBusinessServices = "SpealityBusinessServices",
    SpealityMachinery = "SpealityMachinery",
    StuffingEmployment = "StuffingEmployment",
    ToolsAccessories = "ToolsAccessories",
    Trucking = "Trucking",
    WasteManagement = "WasteManagement",
    IndustrialsEnd = "IndustrialsEnd",
    RealEstateDevelopment = "RealEstateDevelopment",
    RealEstateDiversified = "RealEstateDiversified",
    RealEstateServices = "RealEstateServices",
    ReitDiversified = "ReitDiversified",
    ReitHealtcare = "ReitHealtcare",
    ReitHotelMotel = "ReitHotelMotel",
    ReitIndustrial = "ReitIndustrial",
    ReitMortage = "ReitMortage",
    ReitOffice = "ReitOffice",
    ReitResidental = "ReitResidental",
    ReitRetail = "ReitRetail",
    ReitSpeciality = "ReitSpeciality",
    RealEstateEnd = "RealEstateEnd",
    CommunicationEquipment = "CommunicationEquipment",
    ComputerHardware = "ComputerHardware",
    ConsumerElectronics = "ConsumerElectronics",
    ElectronicComponents = "ElectronicComponents",
    ElectronicDistribution = "ElectronicDistribution",
    ItServices = "ItServices",
    ScientificInstruments = "ScientificInstruments",
    SemiconductorEquipment = "SemiconductorEquipment",
    Semiconductors = "Semiconductors",
    SoftwareApplication = "SoftwareApplication",
    SoftwareInfrastructure = "SoftwareInfrastructure",
    Solar = "Solar",
    TechnologyEnd = "TechnologyEnd",
    UtilitiesDiversified = "UtilitiesDiversified",
    UtilitiesPowerProducers = "UtilitiesPowerProducers",
    UtilitiesRenewable = "UtilitiesRenewable",
    UtilitiesRegulatedElectric = "UtilitiesRegulatedElectric",
    UtilitiesRegulatedGas = "UtilitiesRegulatedGas",
    UtilitiesRegulatedWater = "UtilitiesRegulatedWater",
    UtilitiesEnd = "UtilitiesEnd",
    CommoditiesAgricultural = "CommoditiesAgricultural",
    CommoditiesEnergy = "CommoditiesEnergy",
    CommoditiesMetals = "CommoditiesMetals",
    CommoditiesPrecious = "CommoditiesPrecious",
    CommoditiesEnd = "CommoditiesEnd",
}

export enum EnSwapFlags {
    None = 0,
    ConsiderHolidays = 1,
}

export enum UpdateType6 {
    Add = 0,
    Update = 1,
    Delete = 2,
}

export interface SymbolSyncArgs extends TradePlatformId {
}

export interface TickArgs2 extends TradePlatformId {
    tick: Tick2;
}

export interface Tick2 {
    symbol: string;
    bid: number;
    ask: number;
    /** The price of the last committed transaction. */
    last: number;
    /** Date and time of the tick in milliseconds passed since 01.01 .1970. This fields is not filled in by default (equal to 0) - the history server inserts the server's current trading time when receiving the data. If necessary, the gateway developer can set this date on their own.Using this feature implies 100% correctness of the transferred data time.Therefore, it should be used only when necessary.

datetime_msc has a higher priority than datetime.The server will use this value if it it specified.
If datetime_msc is specified only, datetime value will be filled automatically on its basis(without milliseconds).
If datetime is specified only, datetime_msc value will be filled automatically on its basis(with zero value for milliseconds).


If you specify the time yourself, consider the time zone of the trade server(IMTConTime::TimeZone). For example, if the data feed passes the UNIX time(GMT 0), while the trading server works in GMT+2 time zone, the value should be increased by 60*60*1000*2 (2 hours in milliseconds). */
    lastTime: Date | undefined;
    /** Volume. The volume is recorded in the same form as it is passed by a data provider. A data provider may pass volumes as amounts of contracts (in lots) or as amounts of money. On the trading platform side, this value is interpreted depending on the type of calculation of profit and margin set for a symbol (IMTConSymbol::CalcMode): 

For the IMTConSymbol::TRADE_MODE_FOREX type, the volumes are interpreted as amounts of money.
For all the other type, the volumes are interpreted as amounts of contracts (lots).

For operations with extended volume accuracy, use the 'volume_ext' field.
The 'volume_ext' value has a higher priority than 'volume'. The server will use this value if specified.
When returning volume values, the server fills both fields: with standard and extended accuracy. */
    volumeExt: number;
    flags: EnTickShortFlags;
}

export enum EnTickShortFlags {
    None = "None",
    Raw = "Raw",
    Bid = "Bid",
    Ask = "Ask",
    Last = "Last",
    Volume = "Volume",
    Buy = "Buy",
    Sell = "Sell",
}