[MOD] ORtchimod – Table Mod, Interval Optimization & Backtest working

stable
By Strooth in Trading Bots Published February 2021 👁 2,394 views 💬 3 comments

Description

Moved the slots into tables and added the main code into a go function which is called with optimized for interval and now backtesting works for me Original Post
HaasScript
-- Modified version of Phsai's amazing Simple Market Maker that intended 
-- ONLY FOR BINANCE FUTURES USDT/COIN and BYBIT FUTURES USDT with HEDGE MODE ENABLED
--
-- Consider donating to support our work!
-- Phsai BTC: 3FRx1EkG4T4izrkaS34xeZHJFK4kQefHKf
-- Smokyho BTC: 35KY1GPFtxKoJ6Bzri6sLYQPcmGZhHfRac
-- ORtchi BTC: 1MuMTfRSbVLuBJwz8bhZzhKckoC2iL6dY4
--        ETH: 0x0bafde44120a9512e2e57c9e9b996eab3d8bab31
--        Binance: bnb136ns6lfw4zs5hg4n85vdthaad7hq5m4gtkgf23     MEMO: 105862840
-- --------------------------------------------------------------------------
    EnableHighSpeedUpdates(true)
    HideOrderSettings()
    HideTradeAmountSettings()
    local interval = CurrentInterval()
   -- Check BYBIT or BINANCE
    local getMarket = PriceMarket()
    local isBybit = StringContains(getMarket, 'BYBIT')
     
    -- inputs
    InputGroupHeader('Slots')
        local group = 'Slots'
        local stable = InputTable(
        InputTableOptions('Slots', 1, 1, group),
        InputTableColumn('Slot Count', 1),
        InputTableColumn('Minimum Spread %', 0),
        InputTableColumn('Cancel Distance %', 0.236),
        InputTableColumn('Slot Spread % Mod1', 0.08),
        InputTableColumn('Slot Spread % Mod2', 0.42),
        InputTableColumn('Slot Spread % Mod3', 0.642),
        InputTableColumn('min. % Spread Mod3', 0.2)
        )
        local slotCount =  Parse(stable[1][1], NumberType)
        local minSpread = Parse(stable[1][2], NumberType)
        local slotCancel = Parse(stable[1][3], NumberType)
        local slotSpread_1 = Parse(stable[1][4], NumberType)
        local slotSpread_2 = Parse(stable[1][5], NumberType)
        local slotSpread_3 = Parse(stable[1][6], NumberType)
        local mindist = Parse(stable[1][7], NumberType)
        
       
        InputGroupHeader('Slots Short')
        local okShort = Input('Allow Short', true, 'Allow bot to open Short', group)
        local sstable = InputTable(
        InputTableOptions('Slots Short', 1, 1, group),
        InputTableColumn('Slot Size short Mod1', 5),
        InputTableColumn('Max Cont. % Short Mod1', 0.4),
        InputTableColumn('Slot Size short Mod2', 1),
        InputTableColumn('Max Cont. % Short Mod2', 20),
        InputTableColumn('Slot Size short Mod3', 1),
        InputTableColumn('Max Cont. % Short Mod3', 30)
        )
        local slotSize_1 = Parse(sstable[1][1], NumberType)
        local maxSizeS_1 = Parse(sstable[1][2], NumberType)
        local slotSize_2 = Parse(sstable[1][3], NumberType)
        local maxSizeS_2 = Parse(sstable[1][4], NumberType)
        local slotSize_3 = Parse(sstable[1][5], NumberType)
        local maxSizeS_3 = Parse(sstable[1][6], NumberType)
        
        InputGroupHeader('Slots Long')
        local okLong = Input('Allow Long', true, 'Allow bot to open Long', group)
        local sltable = InputTable(
        InputTableOptions('Slots Long', 1, 1, group),
        InputTableColumn('Slot Size Long Mod1', 5),
        InputTableColumn('Max Cont. % Long Mod1', 0.4),
        InputTableColumn('Slot Size Long Mod2', 1),
        InputTableColumn('Max Cont. % Long Mod2', 20),
        InputTableColumn('Slot Size Long Mod3', 1),
        InputTableColumn('Max Cont. % Long Mod3', 30)
        )
        local slotSizel_1 = Parse(sltable[1][1], NumberType)
        local maxSizeL_1 = Parse(sltable[1][2], NumberType)
        local slotSizel_2 = Parse(sltable[1][3], NumberType)
        local maxSizeL_2 = Parse(sltable[1][4], NumberType)
        local slotSizel_3 = Parse(sltable[1][5], NumberType)
        local maxSizeL_3 = Parse(sltable[1][6], NumberType)
 
        local compound = false
        local wtfBal = true
        local wtfAmount = false

        group = 'Budget'
        InputGroupHeader(group)
        local autoMax = Input('Dynamic Max Open', true, 'Dynamically change max open contracts based on available balance', group)
        local autoSlot = Input('Dynamic Slot Size', true, 'DSSize - Dynamically change slot size favoring trending side.', group)
        local btable = InputTable(
        InputTableOptions('Budget', 1, 1, group),
        InputTableColumn('Max. Open '..AmountLabel(), 1000),
        InputTableColumn('Leverage', 20),
        InputTableColumn('COIN-M Value', 10),
        InputTableColumn('Balance Budget', 0.8),
        InputTableColumn('Position Budget', 0.5),
        InputTableColumn('Slot Size', 1),
        InputTableColumn('Max. Open Divider', 200),
        InputTableColumn('Max. Open Divider', 1000),
        InputTableColumn('Max. Open Divider', 1000)
        )
        local maxSizeM = Parse(btable[1][1], NumberType)
        local leverage = Parse(btable[1][2], NumberType)
        local contVal = Parse(btable[1][3], NumberType)
        local maxBudget = Parse(btable[1][4], NumberType)
        local maxOpen = Parse(btable[1][5], NumberType)
        local slotSizeM = Parse(btable[1][6], NumberType)
        local slotBudget1 = Parse(btable[1][7], NumberType)
        local slotBudget2 = Parse(btable[1][8], NumberType)
        local slotBudget3 = Parse(btable[1][9], NumberType)
        
        group = 'Profit'
        InputGroupHeader(group)
        local tpOrderType = InputOrderType('TP Order Type', MarketOrderType, 'Sellmod  Take Profit', group)
        local ptable = InputTable(
        InputTableOptions('Profit', 1, 1, group),
        InputTableColumn('Take-Profit % Short', 0.25),
        InputTableColumn('Take-Profit % Long', 0.25),
        InputTableColumn('Dynamic Profit', 0.92)
        )
        local takeProfitS = Parse(ptable[1][1], NumberType)
        local takeProfitL = Parse(ptable[1][2], NumberType)
        local dynprofit = Parse(ptable[1][3], NumberType)

        local contsize = contVal

        group = 'Profitmod with the market'
        InputGroupHeader(group)
        local ProfitMod2 =  Input('Profitmod 2 allow', false, 'Deactivates the normal profit mod and activates the alternative profit mod 2', group)
        local oksldyn = Input('Dynamic Profit', false, 'Increases size and gain distance', group)
        local okchle = Input('Change Leverage', false, 'May the leverage be increased?', group)
        local pmtable = InputTable(
        InputTableOptions('Profitmod', 1, 1, group),
        InputTableColumn('Min ROI Slot Short', 500000),
        InputTableColumn('% Buy Price Long', 0.6),
        InputTableColumn('SL % PriceLong', 0.3),
        InputTableColumn('% Sell long', 0.1),
        InputTableColumn('% Buy long Mod', 1.13),
        InputTableColumn('Max Cont. Long Mod', 40),
        InputTableColumn('Min Cont. Long Mod', 10),
        InputTableColumn('Slot Spread % Mod', 0.08),
        InputTableColumn('Increase profit margin', 1.03),
        InputTableColumn('Increase win size', 1.1),
        InputTableColumn('Maximaler Leverage', 100)
        )
        local minroislotshort = Parse(pmtable[1][1], NumberType)
        local maxroislotlong = Parse(pmtable[1][2], NumberType)
        local slroislotlong = Parse(pmtable[1][3], NumberType)
        local sellslotlong = Parse(pmtable[1][4], NumberType)
        local slotSizel_4 = Parse(pmtable[1][5], NumberType)
        local maxSizeL_4 = Parse(pmtable[1][6], NumberType)
        local minSizeL_4 = Parse(pmtable[1][7], NumberType)
        local slotSpread_4 = Parse(pmtable[1][8], NumberType)
        local slminrois = Parse(pmtable[1][9], NumberType)
        local chsize = Parse(pmtable[1][10], NumberType)
        local maxchle = Parse(pmtable[1][11], NumberType)
        
        group = 'Safetymod'
        InputGroupHeader(group)
        local oksafty = Input('Safetymod allow', false, 'Allow bot to open Safetymod, works only with normal Profitmod', group)
        local okbacksafty = Input('Safetysell allow', false, 'Allow bot to sell in the Safetymod', group)
        local smtable = InputTable(
        InputTableOptions(group, 1, 1, group),
        InputTableColumn('Safety Mod1 %', -4),
        InputTableColumn('Safetysize Mod1 ', 0.25),
        InputTableColumn('Max Cont. Short Safety1', 7),
        InputTableColumn('Max Cont. Long Safety1', 7),
        InputTableColumn('Safetymod2 %', -5),
        InputTableColumn('Safetysize2 ', 1.5),
        InputTableColumn('Safetymod3 %', -6),
        InputTableColumn('Safetysize3 ', 2),
        InputTableColumn('Safetymod4 %', -7),
        InputTableColumn('Safetysize4 ', 2.7),
        InputTableColumn('Safetymod5 %', -8),
        InputTableColumn('Safetysize5 ', 3.5),
        InputTableColumn('Safetyprofit2-5 ', 0.01),
        InputTableColumn('Dyn Safety Profit2-5', 0.92),
        InputTableColumn('Safety back %', 0.7),
        InputTableColumn('Safetyprofitsell ', 0.2),
        InputTableColumn('Max Cont. Short Safety2-5', 100),
        InputTableColumn('Max Cont. Long Safety2-5', 100)
        )
        local safty0 = Parse(smtable[1][1], NumberType)
        local saftysize0 = Parse(smtable[1][2], NumberType)
        local maxSizeS_safty0 = Parse(smtable[1][3], NumberType)
        local maxSizeL_safty0 = Parse(smtable[1][4], NumberType)
        local safty2 = Parse(smtable[1][5], NumberType)
        local saftysize2 = Parse(smtable[1][6], NumberType)
        local safty3 = Parse(smtable[1][7], NumberType)
        local saftysize3 = Parse(smtable[1][8], NumberType)
        local safty4 = Parse(smtable[1][9], NumberType)
        local saftysize4 = Parse(smtable[1][10], NumberType)
        local safty = Parse(smtable[1][11], NumberType)
        local saftysize = Parse(smtable[1][12], NumberType)
        local saftyprofit = Parse(smtable[1][13], NumberType)
        local dynprofitsafty = Parse(smtable[1][14], NumberType)
        local backsafty = Parse(smtable[1][15], NumberType)
        local saftyprofitsell = Parse(smtable[1][16], NumberType)
        local maxSizeS_safty = Parse(smtable[1][17], NumberType)
        local maxSizeL_safty = Parse(smtable[1][18], NumberType)
 
        InputGroupHeader('Emergency sale')
        local reduceSize = Input('Size Reduction % ', 0, 'CAUTION! When Max Size Mod 3 is reached, percentage Contracte is sold. Should normally have 0!!!')
        local reduceOrderType = InputOrderType('Reduction Order Type', MarketOrderType, 'Sellmod')
         
       InputGroupHeader('Manual Entries')
     
        local limit_open_short = Input('Open Lmt Order Short', 0, 'Buy short contracts per limit order, price required')
        local limit_preis_short = Input('Price Lmt Order Short', 0, 'Price Limit Order Buy Short Contracte')
        local limit_open_long = Input('Open Lmt Order Long', 0, 'Buy long contracts per limit order, price required')
        local limit_preis_long = Input('Price Lmt Order Long', 0, 'Price Limit Order Buy Long Contracte')
        local limit_open_akt_short = Input('Open Lmt current Price Short', 0, 'Buy short contracts per limit order, current price')
        local limit_open_akt_long = Input('Open Lmt current Price Long', 0, 'Buy long contracts per limit order, current price')
        
        InputGroupHeader('Entry Price Change ')
        local newentryshort = Input('Entry Short change', -1, 'If the entry price is incorrect, it can be changed; after the change, set it back to -1.')
        local newentrylong = Input('Entry Long change', -1, 'If the entry price is incorrect, it can be changed; after the change, set it back to -1.')
        CC_VPM() 
        minSpread = minSpread / 2.0
        local slotCancel_1 =   slotCancel
        local slotCancel_2 =   slotCancel 
        local slotCancel_3 =   slotCancel 
        local slotCancel_4 = slotSpread_4
        local slotSpread = slotSpread_3
        local slotSize = slotSize_3
        local slotSizel = slotSizel_3
        local maxSizeL = maxSizeL_3
        local maxSizeS = maxSizeS_3
        local hedgeMode = true 
        local hedgeRoi = -11111
        local safel = 0
        local safes = 0
        local safesell = 0
        local pamt_l2 = Load('pamt_l2',0)
        local pamt_s2 = Load('pamt_s2',0)
        --------------------------------------------------------------------------------------------
        --------------------------------------------------------------------------------------------
     
    local leverage_save
    local cp
    local TMC
    local MTA
    local profitLabel
    local hedge_longPosId
    local hedge_shortPosId
    local availBal
    local longAmount
    local shortAmount
    local getProfitL
    local getProfitS
    local getProfit
    local usedLong
    local usedShort
    local walletBal
    local botProfit
    local wallMount
    local xchange
    local workBal
    local budgetBal
    local balRatio
    local roundc

    -- wallet check
    local go = function ()
    
        local leverage_save = Load('leverage_save', leverage)
        local cp = CurrentPrice()  
        local TMC = TradeMarketContainer(getMarket)
        local MTA = TMC.minimumTradeAmount
        local profitLabel = ProfitLabel()
        if profitLabel == nil then 
            profitLabel = QuoteCurrency() 
            end
        local hedge_longPosId = Load('hedge_longPosId', NewGuid())
        local hedge_shortPosId = Load('hedge_shortPosId', NewGuid())
        local availBal = WalletAmount(AccountGuid(), profitLabel)
        local longAmount = LongAmount()
        local shortAmount = ShortAmount()
        local getProfitL = GetCurrentProfit(PositionLong)
        local getProfitS = GetCurrentProfit(PositionShort)
        local getProfit = getProfitL + getProfitS
        local usedLong = UsedMargin(AccountGuid(), GetPositionEnterPrice(hedge_longPosId), longAmount, leverage_save)
        local usedShort = UsedMargin(AccountGuid(), GetPositionEnterPrice(hedge_shortPosId), shortAmount, leverage_save)
        local walletBal = WalletAmount(AccountGuid(), profitLabel)
        local botProfit = GetBotProfit()
        
        if isBybit then    
            wallMount = availBal + usedLong + usedShort - getProfit
            xchange = 'BYBIT'
        else 
            wallMount = availBal
            xchange = 'BINANCE'
        end

     -- balance warning
        local walletBal = compound and (wallMount + botProfit) or wallMount
        local workBal = usedLong + usedShort - getProfit
        local budgetBal = maxBudget * walletBal
        local balRatio = budgetBal > 0 and workBal / budgetBal or 0
        local roundc
        if balRatio > 0.5 and balRatio < 0.8 then LogWarning('Working balance is > 50% of Budget!!!') end
        if balRatio > 0.8 then LogWarning('Working balance is > 80% of Budget!!!') end
        Log('Balance Monitor '..xchange..' -> Budget Balance: '..Round(budgetBal, 5)..' '..profitLabel..' | Working Balance: '..Round(workBal, 5)..' '..profitLabel..' | Ratio: '..Round(balRatio, 3))
       
             if profitLabel == 'USD' or profitLabel == 'USDT' then
            maxMax = walletBal * maxBudget * maxOpen / cp.close 
            roundc = 3
        else
            maxMax = walletBal * maxBudget * maxOpen * cp.close / contVal 
            roundc = 0
        end 
    

       
        -- hedge it!
                -- price and data
                local c = ClosePrices()
                local rsi = RSI(c, 9) -- RSI is used to determine which side to start off with. this is to eliminate ghost positions.
                local signal = rsi > 52 and -1 or rsi < 48 and 1 or 0
     
            -- positions
                local hedge_longPosId = Load('hedge_longPosId', NewGuid())
                local hedge_shortPosId = Load('hedge_shortPosId', NewGuid())
     
                local dir_l = GetPositionDirection(hedge_longPosId)
                local aep_l = GetPositionEnterPrice(hedge_longPosId)
                local pamt_l = GetPositionAmount(hedge_longPosId)
                local proi_l = GetPositionROI(hedge_longPosId)
                local dir_s = GetPositionDirection(hedge_shortPosId)
                local aep_s = GetPositionEnterPrice(hedge_shortPosId)
                local pamt_s = GetPositionAmount(hedge_shortPosId)
                local proi_s = GetPositionROI(hedge_shortPosId)
                local profitcurrentlong = GetCurrentProfit(PositionLong)
                local profitcurrentshort = GetCurrentProfit(PositionShort)
                local enterpricelong1 = Load('enterpricelong1',0)
                local enterpriceshort1 = Load('enterpriceshort1',0)
                local enterpricedifflong = Load('enterpricedifflong',0)
                local enterpricediffshort = Load('enterpricediffshort',0)
                local tradeprofitshort = Load('tradeprofitshort',0)
                local tradeprofitlong = Load('tradeprofitlong',0)
                local pricechangelong = Load('pricechangelong', 0)
                local pricechangeshort = Load('pricechangeshort', 0)
                local profitcalcshort = 0
                local profitcalclong = 0
                local enterpricedifflongbuy = 0
                local enterpricediffshortbuy = 0
                local enterpricedifflongsell = 0
                local enterpricediffshortsell = 0
                local posprofitlong = GetPositionProfit (hedge_longPosId)
                local posprofitshort = GetPositionProfit (hedge_shortPosId)
                local enterp2 = AverageEnterPrice(hedge_longPosId)
 
                Log("GetPositionEnterPrice "..aep_l.." AverageEnterPrice "..enterp2)
               
 
     
            -- not using spread if we have a position
                            if pamt_l > 0 or pamt_s > 0 then
                                     minSpread = 0
                            end
     
            -- manage position ids
                             if pamt_l == 0 and IsPositionClosed(hedge_longPosId) then
                                     enterpricelong1 = 0
                                     enterpricedifflongbuy = 0 
                                    enterpricedifflongsell = 0
                                    profitcalclong = 0
                                    tradeprofitlong = 0
                                    pamt_l2 = 0
                                    if IsAnyOrderOpen(hedge_longPosId) then
                                            CancelAllOrders(hedge_longPosId)
                        
                                     else
                                        hedge_longPosId = NewGuid()
                                        dir_l = GetPositionDirection(hedge_longPosId)
                                        aep_l = GetPositionEnterPrice(hedge_longPosId)
                                        pamt_l = GetPositionAmount(hedge_longPosId)
                                        proi_l = GetPositionROI(hedge_longPosId)
                                    end
                             end
                
                if pamt_s == 0 and IsPositionClosed(hedge_shortPosId) then
 
                    enterpriceshort1 = 0
                    enterpricediffshortbuy =  0
                    enterpricediffshortsell = 0
                    profitcalcshort = 0 
                    tradeprofitshort = 0
                    pamt_s2 = 0
                                 if IsAnyOrderOpen(hedge_shortPosId) then
                                     CancelAllOrders(hedge_shortPosId)
                                      else
                                    hedge_shortPosId = NewGuid()
                                    dir_s = GetPositionDirection(hedge_shortPosId)
                                    aep_s = GetPositionEnterPrice(hedge_shortPosId)
                                    pamt_s = GetPositionAmount(hedge_shortPosId)
                                    proi_s = GetPositionROI(hedge_shortPosId)
                                end
                end
            
            -- get pos id
                local getPositionId = function(isLong)
                    return isLong and hedge_longPosId or hedge_shortPosId
                end
 
                     -- Enter price + Profit Calc
 
 
-- Preisanpassung
 
 
if pricechangeshort == 0 and newentryshort > - 1 then
 
enterpriceshort1 = newentryshort
 
pricechangeshort = 1 
 
 
end
 
if pricechangeshort == 1 and  newentryshort  < 0 then
 
pricechangeshort = 0
 
 
end
 
 
if pricechangelong == 0 and newentrylong > - 1 then
 
enterpricelong1 = newentrylong
 
pricechangelong = 1 
 
 
end
 
if pricechangelong == 1 and  newentrylong  < 0 then
 
pricechangelong = 0
 
 
end
 
Save('pricechangelong', pricechangelong)
Save('pricechangeshort', pricechangeshort)
 
 
if pamt_l > 0 then
 
enterpricedifflongbuy = (cp.bid * 100 / enterpricelong1 ) - 100
enterpricedifflongsell = (cp.ask * 100 / enterpricelong1 ) - 100
profitcalclong = (  (1 /enterpricelong1) - (1 /cp.ask)) * pamt_l * contsize
end
 
 
if pamt_s > 0 then 
 
enterpricediffshortbuy =  (enterpriceshort1 * 100 / cp.ask )  - 100
enterpricediffshortsell = (enterpriceshort1 * 100 / cp.bid ) - 100
profitcalcshort = (     (1 / cp.bid) - (1 /enterpriceshort1)  ) * pamt_s * contsize
 
 
end
 
 
local profitpositions = profitcalcshort + profitcalclong
 
 
 
local lastlongp = LastLongPrice()
local lastshortp = LastShortPrice()
local lastexitshortp = LastExitShortPrice()
local lastexitlongp = LastExitLongPrice()
local pamt_l_diff = 0 
local pamt_s_diff = 0
 
 
 
 
    if pamt_l2 > pamt_l then
        pamt_l_diff = pamt_l2 - pamt_l
        local tradeprofitlong1 = pamt_l_diff *  contsize *  (     (1 / lastexitlongp) -(1 / enterpricelong1)  )
        tradeprofitlong = tradeprofitlong + tradeprofitlong1
        pamt_l2 = pamt_l
       
        
    end
 
 
     if pamt_s2 > pamt_s then
        pamt_s_diff = pamt_s2 - pamt_s
        local tradeprofitshort1 = pamt_s_diff  * contsize * ( (1 / enterpriceshort1) -(1 / lastexitshortp))
        tradeprofitshort = tradeprofitshort + tradeprofitshort1
        pamt_s2 = pamt_s
       
        
    end
 
    if pamt_l2 < pamt_l then
 
            
 
            
            pamt_l_diff = pamt_l - pamt_l2
 
        local enterpricelongnew_1 = pamt_l2 * enterpricelong1
 
        local enterpricelongnew_2 = pamt_l_diff * lastlongp
 
        local enterpricelongnew = (enterpricelongnew_1 + enterpricelongnew_2) / pamt_l
 
 
 
 
        pamt_l2 = pamt_l
 
 
 
 
        enterpricelong1 =  enterpricelongnew
 
    end
 
 
      if pamt_s2 < pamt_s then
 
            
 
            
            pamt_s_diff = pamt_s - pamt_s2
 
        local enterpriceshortnew_1 = pamt_s2 * enterpriceshort1
 
        local enterpriceshortnew_2 = pamt_s_diff * lastshortp
 
        local enterpriceshortnew = (enterpriceshortnew_1 + enterpriceshortnew_2) / pamt_s
 
 
 
 
        pamt_s2 = pamt_s
 
 
 
 
        enterpriceshort1 =  enterpriceshortnew
 
    end
     
 
Log('Pricebase cp.bid: '..cp.bid)
 
 Save('enterpricelong1',enterpricelong1)
 Save('enterpriceshort1',enterpriceshort1)
 Save('pamt_l2',pamt_l2)
 Save('pamt_s2',pamt_s2)
 Save('tradeprofitlong',tradeprofitlong)
 Save('tradeprofitshort',tradeprofitshort)
 
     
    -- slot function
                local slot = function(isLong, index, amount, spread, cancelDist, canPlace)
                    local prefix = isLong and 'L' or 'S'
                    local name = prefix .. index
                    local cmd = isLong and PlaceGoLongOrder or PlaceGoShortOrder
                    local priceBase = isLong
                            and cp.bid
                           
                           
                           
                            or cp.ask
                   
                   
                   
                   
                    local spr = minSpread + spread * index
                    local posId = getPositionId(isLong)
                    local aep = isLong and enterpricelong1 or enterpriceshort1
     
                    -- if we have average entry price
                    if aep > 0 then
                        priceBase = isLong
                                and Min(aep, priceBase)
                                or Max(aep, priceBase)
                    end
     
                    -- get price
                    local price = isLong
                            and SubPerc(priceBase, spr)
                            or AddPerc(priceBase, spr)
     
                    local oid = Load(name..'oid', '') -- order id
     
                    if oid != '' then
                        local order = OrderContainer(oid)
     
                        if order.isOpen then
                            local delta = isLong
                                    and Delta(AddPerc(order.price, spr), priceBase)
                                    or Delta(priceBase, SubPerc(order.price, spr))
                            
                            if delta >= cancelDist   then
                                CancelOrder(oid)
                                LogWarning('Delta cancelled '..name)
                            elseif not canPlace then
                                CancelOrder(oid)
                                LogWarning('Not allowed right now '..name)
                            end
                        else
                            oid = ''
                        end
                    else
                        if canPlace then
                            SetFee(Abs(MakersFee())*-1)
                            oid = cmd(price, amount, {type = MakerOrCancelOrderType, note = name, timeout = 3600, positionId = posId})
                        end
                    end
     
                    Save(name..'oid', oid)
                end
     
    -- slot2 function
                local slot2 = function(isLong, index, amount, spread, cancelDist, canPlace)
                    local prefix = isLong and 'L' or 'S'
                    local name = prefix .. index
                    local cmd = isLong and PlaceGoLongOrder or PlaceGoShortOrder
                    local priceBase = isLong
                            and cp.bid
                            or cp.ask
                    local spr =  0
                    local posId = getPositionId(isLong)
                    local aep = isLong and enterpricelong1 or enterpriceshort1
                   -- if we have average entry price
                    if aep > 0 then
                        priceBase = isLong
                                and cp.bid
                            or cp.ask
                    end
               
                    -- get price
                    local price = isLong
                            and cp.bid
                            or cp.ask
     
                    local oid = Load(name..'oid', '') -- order id
     
                    if oid != '' then
                        local order = OrderContainer(oid)
     
                        if order.isOpen then
                            local delta = isLong
                                    and Delta(AddPerc(order.price, spr), priceBase)
                                    or Delta(priceBase, SubPerc(order.price, spr))
                            
                            if delta >= cancelDist then
                                CancelOrder(oid)
                                LogWarning('Delta cancelled '..name)
                            elseif not canPlace then
                                CancelOrder(oid)
                                LogWarning('Not allowed right now '..name)
                            end
                        else
                            oid = ''
                        end
                    else
                        if canPlace then
                            SetFee(Abs(MakersFee())*-1)
                            oid = cmd(cp.close, amount, {type = MakerOrCancelOrderType, note = name, timeout = 3600, positionId = posId})
                        end
                    end
     
                    Save(name..'oid', oid)
                end
 
    -- slot3 function
                local slot3 = function(isLong, index, amount, spread, cancelDist, canPlace)
                    local prefix = isLong and 'L' or 'S'
                    local name = prefix .. index
                    local cmd = isLong and PlaceGoLongOrder or PlaceGoShortOrder
                    local priceBase = isLong
                            and cp.bid
                            or cp.ask
                    local spr =  0
                    local posId = getPositionId(isLong)
                    local aep = isLong and enterpricelong1 or enterpriceshort1
                   -- if we have average entry price
                    if aep > 0 then
                        priceBase = isLong
                                and cp.bid
                            or cp.ask
                    end
               
                    -- get price
                    local price = isLong
                            and cp.bid
                            or cp.ask
     
                    local oid = Load(name..'oid', '') -- order id
     
                    if oid != '' then
                        local order = OrderContainer(oid)
     
                        if order.isOpen then
                            local delta = isLong
                                    and Delta(AddPerc(order.price, spr), priceBase)
                                    or Delta(priceBase, SubPerc(order.price, spr))
                            
                            if delta >= cancelDist then
                                CancelOrder(oid)
                                LogWarning('Delta cancelled '..name)
                            elseif not canPlace then
                                CancelOrder(oid)
                                LogWarning('Not allowed right now '..name)
                            end
                        else
                            oid = ''
                        end
                    else
                        if canPlace then
                            SetFee(Abs(MakersFee())*-1)
                            oid = cmd( limit_preis_long , amount, {type = MakerOrCancelOrderType, note = name, timeout = 3600, positionId = posId})
                        end
                    end
     
                    Save(name..'oid', oid)
                end
 
 
 
 
    -- slot4 function
                local slot4 = function(isLong, index, amount, spread, cancelDist, canPlace)
                    local prefix = isLong and 'L' or 'S'
                    local name = prefix .. index
                    local cmd = isLong and PlaceGoLongOrder or PlaceGoShortOrder
                    local priceBase = isLong
                            and cp.bid
                            or cp.ask
                    local spr =  0
                    local posId = getPositionId(isLong)
                    local aep = isLong and enterpricelong1 or enterpriceshort1
                   -- if we have average entry price
                    if aep > 0 then
                        priceBase = isLong
                                and cp.bid
                            or cp.ask
                    end
               
                    -- get price
                    local price = isLong
                            and cp.bid
                            or cp.ask
     
                    local oid = Load(name..'oid', '') -- order id
     
                    if oid != '' then
                        local order = OrderContainer(oid)
     
                        if order.isOpen then
                            local delta = isLong
                                    and Delta(AddPerc(order.price, spr), priceBase)
                                    or Delta(priceBase, SubPerc(order.price, spr))
                            
                            if delta >= cancelDist then
                                CancelOrder(oid)
                                LogWarning('Delta cancelled '..name)
                            elseif not canPlace then
                                CancelOrder(oid)
                                LogWarning('Not allowed right now '..name)
                            end
                        else
                            oid = ''
                        end
                    else
                        if canPlace then
                            SetFee(Abs(MakersFee())*-1)
                            oid = cmd( limit_preis_short , amount, {type = MakerOrCancelOrderType, note = name, timeout = 3600, positionId = posId})
                        end
                    end
     
                    Save(name..'oid', oid)
                end
 
                
     
            -- update take-profit
                local updateTakeProfit = function(isLong, entryPrice, targetRoi, cancelDist)        
                    local prefix = isLong and 'Long' or 'Short'
                    local name = prefix .. ' Take-Profit'
                    local oid = Load(prefix .. 'tp_oid', '')
                    local timer = Load(prefix .. 'tp_timer', 0)
                    local maxprofit = Load(prefix ..'tp_maxprofit', 0)
                    local maxprofitmin = Load(prefix ..'tp_maxprofitmin', 0)
                    local posId = getPositionId(isLong)
                    local tp_delta = isLong and Delta(entryPrice, cp.bid) or Delta(cp.ask, entryPrice)
                     
 
                   if tp_delta >= targetRoi  and maxprofit < tp_delta then
                    maxprofit = tp_delta
                    maxprofitmin = maxprofit * dynprofit
                   end
 
                   if tp_delta < targetRoi then
                            maxprofit = 0
                            maxprofitmin = 0
 
                   end
                
                   
                  
                    
                    
                    if oid != '' then
                        local order = OrderContainer(oid)
     
                        if order.isOpen then
                            local delta = isLong
                                    and Delta(order.price, cp.close)
                                    or Delta(cp.close, order.price)
                            
                            if delta >= cancelDist then
                                CancelOrder(oid)
                                LogWarning('Delta cancelled '..name)
                            end
                        else
                            if order.isCancelled then
                                timer = 0
                                
                            end
                            
                            oid = ''
                        end
                    else
                        
                       if tp_delta <= maxprofitmin then
                        if tp_delta >= targetRoi and Time() >= timer then
                            SetFee(tpOrderType == MarketOrderType and TakersFee() or Abs(MakersFee())*-1)
                            oid = PlaceExitPositionOrder({type = tpOrderType, note = name, timeout = 3600, positionId = posId})
                            timer = Time() + 180 -- 3min
                            
                        end
                    end
                   end
                    Save(prefix .. 'tp_oid', oid)
                    Save(prefix .. 'tp_timer', timer)
                    Save(prefix .. 'tp_maxprofit', maxprofit)
                    Save(prefix .. 'tp_maxprofitmin', maxprofitmin)
                    
                end
     
     
            -- update position size
                local updatePositionManagement = function(isLong, currentSize, sizeLimit, cancelDist)
                    local prefix = isLong and 'Long' or 'Short'
                    local name = prefix .. ' Size Reduction'
                    local oid = Load(prefix .. 'pos_oid', '')
                    local posId = getPositionId(isLong)
                    local amount = SubPerc(currentSize, 100 - reduceSize) -- take X% of position
                    local price = isLong
                            and cp.ask
                            or cp.bid
                    local cmd = isLong
                            and PlaceExitLongOrder
                            or PlaceExitShortOrder
                    local timer = Load(prefix .. 'pos_timer', Time())
     
                    if oid != '' then
                        local order = OrderContainer(oid)
     
                        if order.isOpen then
                            local delta = isLong
                                    and Delta(order.price, cp.close)
                                    or Delta(cp.close, order.price)
                            
                            if delta >= cancelDist then
                                CancelOrder(oid)
                                LogWarning('Delta cancelled '..name)
                            end
                        else
                            oid = ''
                        end
                    else
                        if currentSize > sizeLimit and Time() >= timer and  reduceSize > 0  then
                            SetFee(reduceOrderType == MarketOrderType and TakersFee() or Abs(MakersFee())*-1)
                            oid = cmd(price, amount, {type = reduceOrderType, note = name, timeout = 3600, positionId = posId})
                            timer = Time() + 120 -- 2min
                        end
                    end
     
                    Save(prefix .. 'pos_oid', oid)
                    Save(prefix .. 'pos_timer', timer)
                end
 
 
 
 
        -- sellsafety
                local sellsafty = function(isLong, amountsell, cancelDist)
                    local prefix = isLong and 'Long' or 'Short'
                    local name = prefix .. ' sellsafty'
                    local oid = Load(prefix .. 'pos_oid', '')
                    local posId = getPositionId(isLong)
                    local amount = amountsell
                    local price = isLong
                            and cp.ask
                            or cp.bid
                    local cmd = isLong
                            and PlaceExitLongOrder
                            or PlaceExitShortOrder
                    local timer = Load(prefix .. 'pos_timer', Time())
     
                    if oid != '' then
                        local order = OrderContainer(oid)
     
                        if order.isOpen then
                            local delta = isLong
                                    and Delta(order.price, cp.close)
                                    or Delta(cp.close, order.price)
                            
                            if delta >= cancelDist then
                                CancelOrder(oid)
                                LogWarning('Delta cancelled '..name)
                            end
                        else
                            oid = ''
                        end
                    else
                        if  Time() >= timer then
                            SetFee(reduceOrderType == LimitOrderType and TakersFee() or Abs(MakersFee())*-1)
                            oid = cmd(price, amount, {type = reduceOrderType, note = name, timeout = 300, positionId = posId})
                            timer = Time() + 60 -- 1min
                        end
                    end
     
                    Save(prefix .. 'pos_oid', oid)
                    Save(prefix .. 'pos_timer', timer)
                end
 
 
 
                -- selllong Profit
                local sellprofit = function(isLong, amountsell, cancelDist)
                    local prefix = isLong and 'Long' or 'Short'
                    local name = prefix .. ' selllongprofit'
                    local oid = Load(prefix .. 'pos_oid', '')
                    local posId = getPositionId(isLong)
                    local amount = amountsell
                    local price = isLong
                            and cp.ask
                            or cp.bid
                    local cmd = isLong
                            and PlaceExitLongOrder
                            or PlaceExitShortOrder
                    local timer = Load(prefix .. 'pos_timer', Time())
     
                    if oid != '' then
                        local order = OrderContainer(oid)
     
                        if order.isOpen then
                            local delta = isLong
                                    and Delta(order.price, cp.close)
                                    or Delta(cp.close, order.price)
                            
                            if delta >= cancelDist then
                                CancelOrder(oid)
                                LogWarning('Delta cancelled '..name)
                            end
                        else
                            oid = ''
                        end
                    else
                        if  Time() >= timer then
                            SetFee(reduceOrderType == LimitOrderType and TakersFee() or Abs(MakersFee())*-1)
                            oid = cmd(price, amount, {type = reduceOrderType, note = name, timeout = 300, positionId = posId})
                            timer = Time() + 60 -- 1min
                        end
                    end
     
                    Save(prefix .. 'pos_oid', oid)
                    Save(prefix .. 'pos_timer', timer)
                end
 
 
              -- selllong Stop loss
                local longstoploss = function(isLong, amountsell, cancelDist)
                    local prefix = isLong and 'Long' or 'Short'
                    local name = prefix .. ' longSL'
                    local oid = Load(prefix .. 'pos_oid', '')
                    local posId = getPositionId(isLong)
                    local amount = amountsell
                    local price = isLong
                            and enterpricelong1 * 1.001
                            or cp.bid
                    local cmd = isLong
                            and PlaceExitLongOrder
                            or PlaceExitShortOrder
                    local timer = Load(prefix .. 'pos_timer', Time())
                   
     
                     if  Time() >= timer then
                            SetFee(reduceOrderType == LimitOrderType and TakersFee() or Abs(MakersFee())*-1)
                        Log("bevor SL")
                            oid = cmd(price, amount, {type = reduceOrderType, note = name, timeout = 120, positionId = posId})
                            timer = Time() + 60 -- 1min 
                             LogWarning("Stop Loss 2 , Price:" ..price.."Size"..amount )
                       end
                    
                   
                     
                    Save(prefix .. 'pos_oid', oid)
                    Save(prefix .. 'pos_timer', timer)
                end
 
       

-- dynamic slot size and max position 
    --max position
 
 
        local maxCheck = autoMax and (maxMax * leverage_save)
        local maxValue = autoMax and (maxCheck > maxSizeM) and maxCheck or maxSizeM
        local maxSize = autoMax and maxValue or maxSizeM
 
        -- check max open  
            if autoMax then
                if maxCheck > maxSizeM then
                    Log('Dynamic Max Open: '..Round(maxCheck, roundc)..' '..AmountLabel())
 
                else        
                    Log('Dynamic Max Open: '..Round(maxCheck, roundc)..' but using default value: '..Round(maxSizeM, roundc)..' '..AmountLabel())
 
                end
                
            
            end 
 
 
 
 
           -- auto slot size
        local slotCheck1 = autoSlot and (maxSize / slotBudget1)
        local slotCheck2 = autoSlot and (maxSize / slotBudget2)                       
        local slotCheck3 = autoSlot and (maxSize / slotBudget3)
        local slotValues1 = autoSlot and (slotCheck1 > slotSize_1) and slotCheck1 or slotSize_1
        local slotValues2 = autoSlot and (slotCheck2 > slotSize_2) and slotCheck2 or slotSize_2
        local slotValues3 = autoSlot and (slotCheck3 > slotSize_3) and slotCheck3 or slotSize_3
        local slotValuel1 = autoSlot and (slotCheck1 > slotSizel_1) and slotCheck1 or slotSizel_1
        local slotValuel2 = autoSlot and (slotCheck2 > slotSizel_2) and slotCheck2 or slotSizel_2
        local slotValuel3 = autoSlot and (slotCheck3 > slotSizel_3) and slotCheck3 or slotSizel_3
 
        local slotSize1 = autoSlot and slotValues1 or slotSize_1
        local slotSize2 = autoSlot and slotValues2 or slotSize_2
        local slotSize3 = autoSlot and slotValues3 or slotSize_3        
        local slotSizel1 = autoSlot and slotValuel1 or slotSizel_1
        local slotSizel2 = autoSlot and slotValuel2 or slotSizel_2
        local slotSizel3 = autoSlot and slotValuel3 or slotSizel_3
        if autoSlot then
           if okShort then    
            if slotCheck1 > slotSize_1 then
                slotSize_1 = slotSize1
                Log('Dynamic Slot S1 Size: '..Round(slotSize1, roundc))
            
            else
                                
                Log('DSSize: S1 '..Round(slotCheck1, roundc)..' But using default value: '..Round(slotSize_1, roundc))
            
            end
            if slotCheck2 > slotSize_2 then
                slotSize_2 = slotSize2
                Log('Dynamic Slot S2 Size: '..Round(slotSize2, roundc))
            
            else
                                
                Log('DSSize: S2 '..Round(slotCheck2, roundc)..' But using default value: '..Round(slotSize_2, roundc))
            
            end
            if slotCheck3 > slotSize_3 then
                slotSize_3 = slotSize3
                Log('Dynamic Slot S3 Size: '..Round(slotSize3, roundc))
            
            else
                                
                Log('DSSize: S3 '..Round(slotCheck3, roundc)..' But using default value: '..Round(slotSize_3, roundc))
            
            end
        end
        if okLong then
        
        if slotCheck1 > slotSizel_1 then
                slotSizel_1 = slotSizel1
                Log('Dynamic Slot L1 Size: '..Round(slotSizel1, roundc))
            
            else
                                
                Log('DSSize: L1 '..Round(slotCheck1, roundc)..' But using default value: '..Round(slotSizel_1, roundc))
            
            end
               if slotCheck2 >= slotSizel_2 then
                slotSizel_2 = slotSizel2
                Log('Dynamic Slot L2 Size: '..Round(slotSizel2, roundc))
            
            else
                                
                Log('DSSize: L2 '..Round(slotCheck2, roundc)..' But using default value: '..Round(slotSizel_2,roundc))
            
            end
               if slotCheck3 > slotSizel_3 then
                slotSizel_3 = slotSizel3
                Log('Dynamic Slot L3 Size: '..Round(slotSizel3, roundc))
            
            else
                                
                Log('DSSize: L3 '..Round(slotCheck3, roundc)..' But using default value: '..Round(slotSizel_3, roundc))
            
            end
       
          end
else
 
 
 if okShort then
 Log('Manual Slot S1 Size: '..Round(slotSize_1, roundc))
 Log('Manual Slot S2 Size: '..Round(slotSize_2, roundc))
 Log('Manual Slot S3 Size: '..Round(slotSize_3, roundc))
 end
 if okLong then
 Log('Manual Slot L1 Size: '..Round(slotSizel_1, roundc))
 Log('Manual Slot L2 Size: '..Round(slotSizel_2, roundc))
 Log('Manual Slot L3 Size: '..Round(slotSizel_3, roundc))
end
end
        
        
         -- manuell Slots
 
      -- Agressiv Mod1
 
 
 
 local slotSpreadl = 0
 local slotSpreads = 0
 local slotCancels = 0
 local slotCancell = 0
 local mod3long = 0
 local mod3short = 0
 
 if autoMax == true and   maxCheck > maxSizeM then
 
      Log("AUTOMATIC MAXIMUM")
 
        maxSizeL_1 = maxCheck * maxSizeL_1 / 100
        maxSizeL_2 = maxCheck * maxSizeL_2  / 100
        maxSizeL_3 = maxCheck * maxSizeL_3  / 100
        maxSizeS_1 = maxCheck * maxSizeS_1 / 100
        maxSizeS_2 = maxCheck * maxSizeS_2  / 100
        maxSizeS_3 = maxCheck * maxSizeS_3  / 100
        maxSizeS_safty0 = maxCheck * maxSizeS_safty0 / 100
        maxSizeS_safty = maxCheck * maxSizeS_safty / 100
        maxSizeL_safty0 = maxCheck * maxSizeL_safty0 / 100
        maxSizeL_safty = maxCheck * maxSizeL_safty / 100
         maxSizeL_4 = maxCheck * maxSizeL_4  / 100
        minSizeL_4 = maxCheck * minSizeL_4 / 100
  
 
        if pamt_l <  maxSizeL_1  then
       
        slotSpreadl = slotSpread_1
        slotCancell = slotCancel_1
          slotSizel = slotSizel_1
      
        end   
        if pamt_l < maxSizeL_2 and pamt_l >= maxSizeL_1 then
       
        slotSizel = slotSizel_2
        slotSpreadl = slotSpread_2
        slotCancell = slotCancel_2
        
        end  
 
        if pamt_l < maxSizeL_3 and pamt_l >= maxSizeL_2 then
        
         slotSizel = slotSizel_3
        slotSpreadl = slotSpread_3
        slotCancell = slotCancel_3
        mod3long = 1
            
 
      
        end  
         
        if pamt_s <  maxSizeS_1  then
       
        slotSpreads = slotSpread_1
        slotCancels = slotCancel_1
         slotSizes = slotSize_1
      
        end   
        if pamt_s < maxSizeS_2 and pamt_s >= maxSizeS_1 then
       
        slotSpreads = slotSpread_2
        slotCancels = slotCancel_2
        slotSizes = slotSize_2
        end  
 
        if pamt_s < maxSizeS_3 and pamt_s >= maxSizeS_2 then
        
        slotSpreads = slotSpread_3
        slotCancels = slotCancel_3
        slotSizes = slotSize_3
        mod3short = 1
            
 
      
        end  
 
else
         Log("MANUAL MAXIMUM")
        maxSizeL_1 = maxSizeM * maxSizeL_1  / 100 
        maxSizeL_2 = maxSizeM * maxSizeL_2   /100 
        maxSizeL_3 = maxSizeM * maxSizeL_3   / 100 
        maxSizeS_1 = maxSizeM * maxSizeS_1  / 100 
        maxSizeS_2 = maxSizeM * maxSizeS_2   /100 
        maxSizeS_3 = maxSizeM * maxSizeS_3   / 100   
         maxSizeL_4 = maxSizeM * maxSizeL_4  / 100
        minSizeL_4 = maxSizeM * minSizeL_4 / 100
        maxSizeS_safty0 = maxSizeM * maxSizeS_safty0 / 100
        maxSizeS_safty = maxSizeM * maxSizeS_safty / 100
        maxSizeL_safty0 = maxSizeM * maxSizeL_safty0 / 100
        maxSizeL_safty = maxSizeM * maxSizeL_safty / 100  
            
 
        if pamt_l <  maxSizeL_1  then
        slotSizel = slotSizel_1
        slotSpreadl = slotSpread_1
        slotCancell = slotCancel_1
 
           
      
        end   
   
        if pamt_s <  maxSizeS_1  then
        slotSizes = slotSize_1
        slotSpreads = slotSpread_1
        slotCancels = slotCancel_1
 
           
      
        end  
 
        -- Medium Mod2
 
        if pamt_l < maxSizeL_2 and pamt_l >= maxSizeL_1 then
        slotSizel = slotSizel_2
        slotSpreadl = slotSpread_2
        slotCancell = slotCancel_2
 
             
      
      end   
 
         if pamt_s < maxSizeS_2 and pamt_s >= maxSizeS_1 then
        slotSizes = slotSize_2
        slotSpreads = slotSpread_2
        slotCancels = slotCancel_2
 
             
      
      end   
        
       
 
         -- Normal Mod3
        if pamt_l < maxSizeL_3 and pamt_l >= maxSizeL_2 then
        slotSizel = slotSizel_3
        slotSpreadl = slotSpread_3
        slotCancell = slotCancel_3
        mod3long = 1
        end
          if pamt_s < maxSizeS_3 and pamt_s >= maxSizeS_2 then
        slotSizes = slotSize_3
        slotSpreads = slotSpread_3
        slotCancels = slotCancel_3
        mod3short = 1
            
 
      
        end      
 
      
        
 end
       
        
   if okLong then    
       Log('LONG Max Size Mod1 '..Round(maxSizeL_1,roundc))
       Log('LONG Max Size Mod2 '..Round(maxSizeL_2,roundc))
       Log('LONG Max Size Mod3 '..Round(maxSizeL_3,roundc))
       Log('LONG Max Start Size Profitmod '..Round(maxSizeL_4,roundc))
       Log('LONG Size Stopp Loss '..Round(minSizeL_4,roundc))
       Log('LONG SlotSpread '..Round(slotSpreadl,2))
    
 
     if oksafty then
               Log("LONG Max Size Safetymod 1 "..Round(maxSizeL_safty0,roundc))
               Log("LONG Max Size Safetymod 2-5 "..Round(maxSizeL_safty,roundc))
      end
    
    end
     if okShort then   
       Log('SHORT Max Size Mod1 '..Round(maxSizeS_1,roundc))
       Log('SHORT Max Size Mod2 '..Round(maxSizeS_2,roundc))
       Log('SHORT Max Size Mod3 '..Round(maxSizeS_3,roundc))
      
       if oksafty then
           Log("SHORT Max Size Safetymod 1 "..Round(maxSizeS_safty0,roundc))
           Log("SHORT Max Size Safetymod 2-5 "..Round(maxSizeS_safty,roundc))
        end
    
    
    
    end


          local maxgewinn = Load('maxgewinn', 0)
          local mingewinn = Load('mingewinn', 0)
          local safesell = Load('safesell', 0)
          local difflong = 0
           local diffshort = 0
           local amountsell = 0

if oksafty == true and ProfitMod2 == false  then
 
        -- Safty 1
         
                 if enterpricedifflongbuy <= safty0 and  enterpricedifflongbuy > safty and pamt_l * saftysize0 < maxSizeS_safty0 and pamt_s < pamt_l * saftysize0 and enterpricediffshortsell >= 0 and safesell == 0 then
              
                    difflong = ((pamt_l * saftysize0) - pamt_s)
 
                            if maxSizeS_safty0 >= (pamt_s + difflong) then
                         
                            Log('Repurchase Safety1 Number Short - not maximum' ..difflong)
                            Log('Size Long' ..pamt_l)
                             Log('Size Short' ..pamt_s)
                              Log('maxSizeS_safety0' ..maxSizeS_safty0)
                             Log('safetysize0' ..saftysize0)
                            slot2(false, 0, difflong , 0, 0.01,  proi_s >= -10000 )   
                            end
                             if maxSizeS_safty0 < (pamt_s + difflong) then
                                      difflong = maxSizeS_safty0 - pamt_s
                                          if difflong > 0 then
                                                Log('Repurchase Safety1 Number Short - Maximum' ..difflong)
                                                 Log('Size Long' ..pamt_l)
                                                 Log('Size Short' ..pamt_s)
                                                Log('maxSizeS_safety0' ..maxSizeS_safty0)
                                                Log('safetysize0' ..saftysize0)
                                                slot2(false, 0, difflong , 0, 0.01,  proi_s >= -10000 ) 
                                            end
                                end
                    end
 
 
 
         if enterpricediffshortbuy <= safty0 and  enterpricediffshortbuy > safty2 and pamt_l * saftysize0 < maxSizeL_safty0 and pamt_l < pamt_s * saftysize0 and enterpricedifflongsell >= 0  and safesell == 0 then
              
          diffshort = ((pamt_s * saftysize0) - pamt_l)
 
          
          
 
 
                    if maxSizeL_safty0 >= (pamt_l + diffshort) then
 
                        Log('Repurchase Safety1 Number Long - not Maximum' ..diffshort)
                         Log('Size Long' ..pamt_l)
                            Log('Size Short' ..pamt_s)
                        Log('maxSizeL_safety0' ..maxSizeL_safty0)
                             Log('safetysize0' ..saftysize0)
                        slot2(true, 0, diffshort, 0, 0.01, proi_l >= -10000  )   
 
                     end
                        if maxSizeL_safty0 < (pamt_l + diffshort) then
                        diffshort = maxSizeL_safty0 - pamt_l
                                 if diffshort > 0 then
                                         Log('Repurchase Safety1 Number Long - Maximum' ..diffshort)
                                         Log('Size Long' ..pamt_l)
                                        Log('Size Short' ..pamt_s)
                                        Log('maxSizeL_safety0' ..maxSizeL_safty0)
                                            Log('safetysize0' ..saftysize0)
                                        slot2(true, 0, diffshort, 0, 0.01, proi_l >= -10000  )  
                                     end
                        end
        end
            if enterpricedifflongsell < safty0 and enterpricedifflongsell > safty2 + backsafty and pamt_l * saftysize2  >=  pamt_s and enterpricediffshortsell >= saftyprofitsell and okbacksafty then
               modsaftyl = 1
               amountsell =  pamt_s - pamt_l * saftysize0
               sellsafty(false, amountsell, slotCancel)
               Log('Sell short Safty 1' ..amountsell)
 
             end
             if enterpricedifflongsell > safty0 then
                    modsaftyl = 0
            end
            if enterpricediffshortsell > safty0 then
                    modsaftys = 0
            end
            if enterpricediffshortsell < safty0 and enterpricediffshortsell >= safty2 + backsafty  and pamt_s * saftysize2  >=  pamt_l and enterpricedifflongsell  >= saftyprofitsell and okbacksafty  then
                modsaftys = 1
                amountsell = pamt_l - pamt_s * saftysize0
                sellsafty(true, amountsell, slotCancel)
                Log('Sell long Safty 1' ..amountsell)
             end
        
        -- Safty 2-5
        local modsaftyl = Load('modsaftyl', 0)
        local modsaftys = Load('modsaftys', 0)
        if enterpricediffshortsell > safty2 then
             safes = 0
             else 
             safes = 1
            end
                
         if enterpricedifflongsell > safty2 then
             safel = 0
             else 
             safel =1
            end
 
  -- Safty 2
                  if enterpricedifflongsell < safty2 and enterpricedifflongsell > safty3 + backsafty and pamt_l * saftysize3  >=  pamt_s and enterpricediffshortsell >=  saftyprofitsell  and okbacksafty then
               modsaftyl = 2
               amountsell = pamt_s - pamt_l * saftysize2 
               sellsafty(false, amountsell, slotCancel)
               Log('Sell short Safety 2' ..amountsell)
 
               end
              if enterpricedifflongsell <= safty2 and enterpricedifflongsell > safty3 and pamt_l * saftysize2  >  pamt_s and enterpricediffshortsell >= 0  and safesell == 0 then
            
              modsaftyl = 2
               difflong = ((pamt_l * saftysize2) - pamt_s)
                  if difflong + pamt_s <=   maxSizeS_safty then
                    slot2(false, 0, difflong , 0, 0.01,  proi_s >= 0 ) 
                  else
                   difflong = maxSizeS_safty - pamt_s
                   slot2(false, 0, difflong , 0, 0.01,  proi_s >= 0 )
                  end
                Log('Buy short Safety 2' ..difflong)
              end
             if enterpricediffshortsell < safty2 and enterpricediffshortsell >= safty3 + backsafty and pamt_s * saftysize3  >=  pamt_l and  enterpricedifflongsell  >= saftyprofitsell  and okbacksafty then
                 modsaftys = 2
                 amountsell = pamt_l - pamt_s * saftysize2 
               sellsafty(true, amountsell, slotCancel)
               Log('Sell long Safety 2' ..amountsell)
             end
 
              if enterpricediffshortsell < safty2 and enterpricediffshortsell > safty3 and pamt_s * saftysize2 >  pamt_l  and proi_l >= 0  and safesell == 0  then
                        modsaftys = 2
                        diffshort = ((pamt_s * saftysize2) - pamt_l)
                    if diffshort + pamt_l <=   maxSizeL_safty then
                          slot2(true, 0, diffshort, 0, 0.01, proi_l >= 0  ) 
                   
                   else
                      diffshort = maxSizeL_safty - pamt_l
                       slot2(true, 0, diffshort, 0, 0.01, proi_l >= 0  )
                    end
                   Log('Buy long Safety 2' ..diffshort) 
              end 
 
 
 
          
  -- Safty 3
                 if enterpricedifflongsell < safty3 and enterpricedifflongsell > safty4 + backsafty and pamt_l * saftysize4  >=  pamt_s and enterpricediffshortsell  >=  saftyprofitsell and okbacksafty  then
               amountsell = pamt_s - pamt_l * saftysize3 
               sellsafty(false, amountsell, slotCancel)
                Log('Sell short Safety 3' ..amountsell)
               modsaftyl = 3
               end
 
 
              if enterpricedifflongsell <= safty3 and enterpricedifflongsell > safty4 and pamt_l * saftysize3  >  pamt_s and enterpricediffshortsell >= 0  and safesell == 0 then
            
               modsaftyl = 3
               difflong = ((pamt_l * saftysize3) - pamt_s)
                  if difflong + pamt_s <=   maxSizeS_safty then
                    slot2(false, 0, difflong , 0, 0.01,  proi_s >= 0 ) 
                  else
                   difflong = maxSizeS_safty - pamt_s
                   slot2(false, 0, difflong , 0, 0.01,  proi_s >= 0 )
                  end
                 Log('Buy short Safety 3' ..difflong)    
              end
            
               if enterpricediffshortsell < safty3 and enterpricediffshortsell > safty4 + backsafty and pamt_s * saftysize4  >=  pamt_l  and enterpricedifflongsell  >= saftyprofitsell  and okbacksafty then
                 modsaftys = 3
                 amountsell = pamt_l - pamt_s * saftysize3 
               sellsafty(true, amountsell, slotCancel)
               Log('Sell long Safety 3' ..amountsell)
             end
              if enterpricediffshortsell < safty2 and enterpricediffshortsell > safty3 and pamt_s * saftysize3 >  pamt_l  and proi_l >= 0   and safesell == 0 then
                        modsaftys = 3
                        diffshort = ((pamt_s * saftysize3) - pamt_l)
                    if diffshort + pamt_l <=   maxSizeL_safty then
                          slot2(true, 0, diffshort, 0, 0.01, proi_l >= 0  ) 
                   
                   else
                      diffshort = maxSizeL_safty - pamt_l
                       slot2(true, 0, diffshort, 0, 0.01, proi_l >= 0  )
                    end
                  Log('Buy long Safety 3' ..diffshort)  
              end 
 
 
           -- Safty 4
 
              if enterpricedifflongsell < safty4 and enterpricedifflongsell > safty + backsafty and pamt_l * saftysize  >=  pamt_s and enterpricediffshortsell  >= saftyprofitsell   and okbacksafty then
              
               modsaftyl = 4
               amountsell = pamt_s - pamt_l * saftysize4 
               sellsafty(false, amountsell, slotCancel)
                Log('Sell short Safety 4' ..amountsell)
               end
               if enterpricedifflongsell <= safty4 and enterpricedifflongsell > safty and pamt_l * saftysize4  >  pamt_s and enterpricediffshortsell >= 0  and safesell == 0 then
            
              
               modsaftyl = 4
               difflong = ((pamt_l * saftysize4) - pamt_s)
                  if difflong + pamt_s <=   maxSizeS_safty then
                    slot2(false, 0, difflong , 0, 0.01,  proi_s >= 0 ) 
                  else
                   difflong = maxSizeS_safty - pamt_s
                   slot2(false, 0, difflong , 0, 0.01,  proi_s >= 0 )
                  end
                    Log('Buy short Safety 4' ..difflong) 
              end
             if enterpricediffshortsell < safty4 and enterpricediffshortsell > safty + backsafty and pamt_s * saftysize  >=  pamt_l and enterpricedifflongsell  >=  saftyprofitsell and okbacksafty  then
                modsaftys = 4
                 amountsell = pamt_l - pamt_s * saftysize4 
               sellsafty(true, amountsell, slotCancel)
                Log('Sell long Safety 4' ..amountsell)
             end
 
              if enterpricediffshortsell < safty4 and enterpricediffshortsell > safty and pamt_s * saftysize4 >  pamt_l  and proi_l >= 0  and safesell == 0  then
                        modsaftys = 4
                        diffshort = ((pamt_s * saftysize4) - pamt_l)
                    if diffshort + pamt_l <=   maxSizeL_safty then
                          slot2(true, 0, diffshort, 0, 0.01, proi_l >= 0  ) 
                   
                   else
                      diffshort = maxSizeL_safty - pamt_l
                       slot2(true, 0, diffshort, 0, 0.01, proi_l >= 0  )
                    end
                   Log('Buy long Safety 4' ..diffshort) 
              end 
 
 
 
          
          -- Safty 5
 
 
              
              if enterpricedifflongsell <= safty and pamt_l * saftysize  >  pamt_s and enterpricediffshortsell >= 0  and safesell == 0 then
            
               modsaftyl = 5
               difflong = ((pamt_l * saftysize) - pamt_s)
                  if difflong + pamt_s <=   maxSizeS_safty then
                    slot2(false, 0, difflong , 0, 0.01,  proi_s >= 0 ) 
                  else
                   difflong = maxSizeS_safty - pamt_s
                   slot2(false, 0, difflong , 0, 0.01,  proi_s >= 0 )
                  end
                    
              end
            
 
              if enterpricediffshortsell < safty  and pamt_s * saftysize >  pamt_l  and enterpricedifflongsell >= 0   and safesell == 0 then
                        modsafty5 = 5
                        diffshort = ((pamt_s * saftysize) - pamt_l)
                    if diffshort + pamt_l <=   maxSizeL_safty then
                          slot2(true, 0, diffshort, 0, 0.01, proi_l >= 0  ) 
                   
                   else
                      diffshort = maxSizeL_safty - pamt_l
                       slot2(true, 0, diffshort, 0, 0.01, proi_l >= 0  )
                    end
                   
              end 
        
            Log('Safetymod long'..modsaftyl)
            Log('Safetymod short'..modsaftys)
            
           Save('modsaftyl', modsaftyl)
           Save('modsaftys', modsaftys)
 
 
          -- Profit Safty 
 
          local maxgewinn = Load('maxgewinn', 0)
          local mingewinn = Load('mingewinn', 0)
          local safesell = Load('safesell', 0)
 
          local gewinn_s = profitcalcshort
          local gewinn_l = profitcalclong
 
                 
         
         local  gewinn =  posprofitshort + posprofitlong
                   
          if maxgewinn < gewinn  and gewinn >= saftyprofit then
                 maxgewinn = gewinn
                 mingewinn = maxgewinn * dynprofitsafty
          end
 
          if gewinn < saftyprofit then
               maxgewinn = 0
               mingewinn = 0
          end
           
          
           if gewinn > saftyprofit and ((enterpricediffshortsell < safty and pamt_l > pamt_s) or (enterpricedifflongsell < safty and pamt_s > pamt_l) ) then
                  if gewinn <= mingewinn then
                            
                            safesell = 1
                            maxSizeL = 0
                            maxSizeS = 0
                            reduceSize = 100
                  end
           end
          
 
          if safesell == 1  and pamt_l == 0 and pamt_s ==0 then
 
                    safesell = 0
 
          end 
 
 
         if safesell == 1  then
                            maxSizeL = 0
                            maxSizeS = 0
                            reduceSize = 100
         end 
                 
                     Log('Dissolve Safetymod, sell everything when 1 - '..safesell)
                      Log('Safetymod Profit'..gewinn)
                      Log('Safetymod Max Profit'..maxgewinn)
                       Log('Safetymod Min Profit'..mingewinn)
 
           Save('maxgewinn', maxgewinn)
           Save('mingewinn', mingewinn)
           Save('safesell', safesell)
           
end
       
--  Buy Limit current Price
local limit_open_akt_long_now = 0
            
            if limit_open_akt_long > 0  and limit_long_akt_aktiv != 1 then
                
                limit_open_akt_long_now =  limit_open_akt_long
                
                slot2(true, 42, limit_open_akt_long_now , 0, 0.2, proi_l >= hedgeRoi  )
 
                limit_long_akt_aktiv = 1 
                
                limit_open_akt_long_now = 0
 
         
 
 
                            end  
 
                
 
            if limit_open_akt_long == 0 then
 
              limit_long_akt_aktiv = 0
 
            end
          
             local limit_open_akt_short_now = 0
          
            if limit_open_akt_short > 0  and limit_short_akt_aktiv != 1  then
                limit_open_akt_short_now =  limit_open_akt_short
                slot2(false, 42, limit_open_akt_short_now , 0, 1, proi_s >= hedgeRoi  )
                 limit_short_akt_aktiv = 1 
                  limit_open_akt_short_now = 0
                
             end       
 
            if limit_open_akt_short == 0 then
 
              limit_short_akt_aktiv = 0
 
          end
            -- Buy Limit select Price
 
            local limit_open_long_now = 0
            
            if limit_open_long > 0 and limit_preis_long > 0 and limit_long_aktiv != 1 then
                
                limit_open_long_now =  limit_open_long
                
                slot3(true, 42, limit_open_long_now , 0, 1, proi_l >= hedgeRoi  )
 
                limit_long_aktiv = 1 
                
                limit_open_long_now = 0
 
        
               
 
 
                            end  
 
                
 
            if limit_open_long == 0 then
 
              limit_long_aktiv = 0
 
            end
 
            local limit_open_short_now = 0
          
            if limit_open_short > 0 and limit_preis_short > 0 and limit_short_aktiv != 1  then
                limit_open_short_now =  limit_open_short
                slot4(false, 42, limit_open_short_now , 0, 1, proi_s >= hedgeRoi  )
                 limit_short_aktiv = 1 
 
                 
             end       
 
            if limit_open_short == 0 then
 
              limit_short_aktiv = 0
 
          end  
      
 
 
if ProfitMod2 == true and okShort == false and okLong == true then
Log("ProfitMod2")
             -- longmod aktiv
            local longmod = Load('longmod', 0)
            local maxroislotlong_save = Load('maxroislotlong_save', maxroislotlong)
            local slroislotlong_save = Load('slroislotlong_save', slroislotlong)
            local maxSizeL_4_save = Load('maxSizeL_4_save', maxSizeL_4)
            local minSizeL_4_save = Load('minSizeL_4_save', minSizeL_4)
            
            
            
          if  enterpricelong1 * ((100 + maxroislotlong_save) /100 ) < cp.ask  and aep_l > 0 then
             longmod = 1
             Log("Profitmod activates")
            
          end
 
   if pamt_l == 0 then
   longmod = 0
   maxroislotlong_save = maxroislotlong
   slroislotlong_save = slroislotlong
   maxSizeL_4_save = maxSizeL_4
   minSizeL_4_save = minSizeL_4
   leverage_save = leverage
   minSizeL_4_save = minSizeL_4
   end
 
      -- Sell longmod
 
   if longmod == 1 and pamt_l >= maxSizeL_4_save and enterpricelong1 * ((100 + maxroislotlong_save) /100 ) < cp.bid  then
 
     amountsell = Round((pamt_l * sellslotlong), roundc)
 
    sellprofit(true, amountsell, slotCancel_4)
    LogWarning ("LONGMOD SELL"..amountsell)
    if oksldyn  then
             maxroislotlong_save = maxroislotlong_save * slminrois
             slroislotlong_save = slroislotlong_save * slminrois
             maxSizeL_4_save = maxSizeL_4_save * chsize
             LogWarning ("Profit increases! Profit: "..maxroislotlong_save.."% SL: "..slroislotlong_save.."% Maximum Size Profitmod "..maxSizeL_4_save.."Contracte" )
             
 
                   if okchle and  maxSizeL_4_save >= maxCheck and maxchle > leverage_save  then
                     
                      leverage_save = leverage_save + 1
 
 
                     
                   
                   end
                    if okchle and  maxSizeL_4_save >= maxCheck and maxchle <= leverage_save  then
                       maxSizeL_4_save = maxCheck
                    end
   end
 
end
                    if longmod == 0 then
 
                      
                        maxroislotlong_save = maxroislotlong
                         slroislotlong_save = slroislotlong
                        maxSizeL_4_save = maxSizeL_4
                         minSizeL_4_save = minSizeL_4
                         leverage_save = leverage
                          minSizeL_4_save = minSizeL_4
                         if pamt_l > maxSizeL_4_save then
                          maxSizeL_4_save = pamt_l
                         end
 
 
                     end 
 
 
 
if longmod == 1 and  enterpricelong1 *  ((100 + slroislotlong_save) /100 ) >= cp.bid  then
 
       
        
        amountsell = Round((pamt_l - minSizeL_4_save), roundc)
                    
                     
                     LogWarning ("STOP LOSS "..amountsell.." Profitnmod deactivated")
                     if amountsell >= 1 then
                     longstoploss(true, amountsell, 0.4)
                       end
                     if pamt_l <= minSizeL_4_save then
                          longmod = 0
                        if slminrois > 1 then
                            maxroislotlong_save = maxroislotlong
                            slroislotlong_save = slroislotlong
                            maxSizeL_4_save = maxSizeL_4
                           
                            leverage_save = leverage
                             LogWarning ("Profit margin set to start! Profit: "..maxroislotlong_save.."% SL: "..slroislotlong_save.."% Profitmod auf "..Round(maxSizeL_4_save,0).."Contracte")
                        
                     end
                     end
                    
end
 
 
LogWarning("Profitmod Start: "..maxroislotlong_save.."% Stopp Loss "..slroislotlong_save.."% Maximum Size Profitmod "..Round(maxSizeL_4_save,0).." LONGMOD AKTIV:"..longmod )
Save('longmod', longmod)
Save('maxroislotlong_save', maxroislotlong_save)
Save('slroislotlong_save', slroislotlong_save)
Save('maxSizeL_4_save', maxSizeL_4_save)
Save('minSizeL_4_save', minSizeL_4_save)
 
 
      if enterpricelong1  * ((100 + maxroislotlong_save) /100 ) < cp.ask and pamt_l < maxSizeL_4_save  then
             local amountbuy = Round(((pamt_l * slotSizel_4) - pamt_l), roundc)
 
            slot2(true, 20, amountbuy, slotSpread_4, slotCancel_4, ( proi_s >= hedgeRoi))-- long slot
            end
 
 
else
Log("ProfitMod1")
   if safel == 0 and safes == 0 and safesell == 0   then
            
                updateTakeProfit(true, enterpricelong1, takeProfitL, slotCancel)
                updateTakeProfit(false, enterpriceshort1, takeProfitS, slotCancel)
            end
 
            leverage_save = leverage
 end
 
Save('leverage_save', leverage_save)
 
 
 
            -- da logica
               
                -- take profit
         
                -- risk management
 
 
                if safesell ==1 or reduceSize > 0 then
                updatePositionManagement(true, pamt_l, maxSizeL, slotCancel)
                updatePositionManagement(false, pamt_s, maxSizeS, slotCancel)
     
           end
 
 
 
                -- update slots
          
           if okLong == true then
          
            if mod3long == 1 and enterpricedifflongsell >= mindist then
                Log('Mod 3 Long Distance too small, no repurchasing!')
              else
            
            if safel == 1 or safesell == 1 or pamt_l >= maxSizeL_3 then
                            Log('Max long or saftymod')
             else
 
                  
              
                for i = 1, slotCount do
                    slot(true, i, slotSizel, slotSpreadl, slotCancell, (pamt_s == 0 and signal == 1) or  proi_s >= hedgeRoi)-- long slot
                end
            end
            end
           end
           
if okShort == true then
         
            if mod3short == 1 and enterpricediffshortsell >= mindist then
                Log('Mod 3 Short Distance too small, no repurchasing!')
              else
            if safes == 1 or safesell == 1 or pamt_s >= maxSizeS_3  then 
                Log('Max short or saftymod')
 
            else
 
             
                for i = 1, slotCount do
                    slot(false, i, slotSizes , slotSpreads, slotCancels, (pamt_l == 0 and signal == -1) or proi_l >= hedgeRoi) -- short slot
                end
           end
          end
          end
                if enterpricelong1 > 0 then
                    local posId = getPositionId(true)
                    Plot(0, 'AvgEP Long', enterpricelong1, {c=Teal, id=posId, w=2})
                end
     
                if enterpriceshort1 > 0 then
                    local posId = getPositionId(false)
                    Plot(0, 'AvgEP Short', enterpriceshort1, {c=Purple, id=posId, w=2})
                end
             if okLong then Log('Size LONG '..pamt_l) end 
             if okShort then  Log('Size SHORT '..pamt_s)  end
             if okLong then  Log('profitcalclong aktuell '..Parse(profitcalclong, StringType)) end
             if okShort then  Log('profitcalcshort aktuell'..Parse(profitcalcshort, StringType)) end
             LogWarning('Positions Profit: '..Parse(profitpositions, StringType)) 
             if okLong then  LogWarning('LONG Difference Entry '..Parse(enterpricedifflongsell, StringType).."%") end
             if okLong then  LogWarning('LONG own Enter Price: '..Parse(enterpricelong1, StringType)) end
             if okShort then   LogWarning('SHORT Difference Entry '..Parse(enterpricediffshortsell, StringType).."%") end
             if okShort then  LogWarning('SHORT own Enter Price: '..Parse(enterpriceshort1, StringType)) end
             
              Log("Leverage: "..leverage_save)
              
            
             
              
              
          
              
              Save('hedge_longPosId', hedge_longPosId)
              Save('hedge_shortPosId', hedge_shortPosId)
              Log(' ')
end


OptimizedForInterval(interval, go)

3 Comments

Sign in to leave a comment.

A
alkilany about 4 years ago

Hi

Can I ask what the platform to use the code

Thanks

S
Strooth almost 4 years ago

HTS v3

J
JeffVernon almost 4 years ago

:fire: