GBLogSplitter.psm1

Function Clean-Code {
    <#
         .SYNOPSIS
            Cleans up Gunbot Log syntax
    #>

    Param (
        [Parameter(Mandatory=$true)]
        [Parameter(ValueFromPipelineByPropertyName)]
        [String]$Code
    )
    $Code1 = $Code -replace "\[[0-9;]*m",""
    $Code2 = $Code1 -replace '\u001B', ''
    write-output $code2
}

Function Split-GBLog {
    <#
         .SYNOPSIS
            Get Split Gunbot logs into seperate files
     
    #>

    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$false)]
        [switch]$ClearExisting,
        [Parameter(Mandatory=$false)]
        [switch]$JustContinue,
        [Parameter(Mandatory=$false)]
        [switch]$TailLogs,
        [Parameter(Mandatory=$false)]
        [string]$GBLogName='out.log'
    )

    #region Encoding
    $PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }
    $OutputEncoding = [System.Text.Encoding]::UTF8
    #endregion


    Function Clean-Code {
        Param (
            [Parameter(ValueFromPipelineByPropertyName)]
            [String]$Code
        )
        $Code1 = $Code -replace "\[[0-9;]*m",""
        $Code2 = $Code1 -replace '\u001B', ''
        write-output $code2
    }

    cls;Get-Art #-time $true -sleep $true

    #region PathsParams

    $GBPath = get-location
    $SplitPath = (join-path $GBPath 'LogSplitter')
    $GunthyLog =  (join-path $GBPath $GBLogName)
    $BareTail =  (join-path $GBPath 'baretail.exe')
    $lastLog = (join-path $SplitPath 'LogFile.json')
    $LaunchDone=$false
    $LogList = @()
    $SkipCount=0
    $i=1
    $CurrentPlace = '' | Select 'LastParsedLine','Name','CreateDate','LineText'


    if (!(test-path $GunthyLog ))
    {
        Write-warning "$GunthyLog is missing. use -GBLogName or edit file to specify your GB log name"
        break
    } else {
        $CurrentLogFile = Get-Item $GunthyLog
        $TotalLines = (get-content $CurrentLogFile.FullName).count
    }

    if (!(Test-Path $SplitPath ))
    {
        New-Item $SplitPath -ItemType directory 
    } 
    elseif ($ClearExisting -eq $true)
    {
        Remove-Item $SplitPath -Recurse -Force -Confirm:$false
    }

    #endregion

    #region Restart Logging Logic"
    if (!($JustContinue))
    {
        if (test-path $lastLog) {
            write-host "`nAttempting to check if log $gblogname is the same..." #-NoNewline; sleep 0.8; write-host "chiill Winston"
            $LastLogFile = Get-Content $lastLog | ConvertFrom-Json
            $FindLine = clean-code (get-content $CurrentLogFile.FullName | select -Index ($LastLogFile.LastParsedLine))   

            if ($LastLogFile.LineText -eq $FindLine)
            {
                write-host "`nLog file match detected, jumping to line $($LastLogFile.LastParsedLine)"
                $SkipCount = $LastLogFile.LastParsedLine 
                $i=$SkipCount+1
                sleep 1
            } 
            else 
            {
                Write-Host "New Log detected, starting from the beginning"
                sleep 1
            }
        }
    } 
    else
    {
        write-host "JustContinue Switch Specfied, jumping to line $TotalLines in $GBLogname"
        $SkipCount = $TotalLines
        $i=$SkipCount+1
    }
    #endregion

    Get-Content $GunthyLog -wait | select -Skip ($SkipCount)  | % {
        $line = $_
        if ($line -like "*Round #*")
        {
            $RoundHeader = $Line.Split(' ')
            $Pair = $RoundHeader[1]
            $GBVersion = $RoundHeader[0]
            $round =   $RoundHeader[4]
        }
        if ($line -like "*Scanning * for trading opportunities*")
        {
            $Exchange = ($Line.Split(' ')[6])
           
        }
        if ($Pair -ne $null -and $exchange -ne $null) {
            $ExchangeLogs = (join-path $SplitPath $Exchange) 
            if (!(Test-Path $ExchangeLogs))
            {
                New-Item $ExchangeLogs -ItemType directory 
                New-Item $($ExchangeLogs+ '\Data')  -ItemType directory 
            }
            $ExchangeCSVData = join-path (join-path $SplitPath  $Exchange) "Data\$($Exchange)_Data.csv"
         
            $PairLogs = $ExchangeLogs 

            if ($Pair -ne '' -or $Pair  -ne $null) {
                $PairLog  = [System.IO.Path]::Combine($ExchangeLogs,  ($Exchange.Substring(0,3).toupper() + '_' + $Pair + '.log'))
            }
            if (!(test-path $PairLog))
            {
                "" | out-file $PairLog  -Encoding utf8
                if ($LaunchBareTail -eq $true -and  $Round -eq 1)
                {
                    $LogList += $Pairlog
                }
            }
            if ($TailLogs -eq $true -and $LaunchDone -ne $true -and $Round -gt 1)
            {
                if (Test-Path $BareTail) 
                {
                    $LaunchMe = $LogList -join " "
                    invoke-expression ($BareTail +' ' + $LaunchMe )
                    $LaunchDone = $true
                }
                else
                {
                    write-warning "baretail.exe not found. Download it and place it in $GBPath..."
                    Pause
                    Write-host "....or dont. "
                    sleep 1
                }
            }

            if ($line -ne $LastLine) 
            {    
                $Unencoded = Clean-Code ($line)            
                  
                $FileMode = [System.IO.FileMode]::Append
                $FileAccess = [System.IO.FileAccess]::Write
                $FileShare = [IO.FileShare]::Read
                $FileStream = New-Object IO.FileStream($PairLog, $FileMode, $FileAccess, $FileShare)
                $StreamWriter = New-Object System.IO.StreamWriter($FileStream)
                $StreamWriter.WriteLine($Unencoded)
                $StreamWriter.Dispose()
                $FileStream.Dispose()
            
                switch -wildcard ($Unencoded )
                {
                    "*Last Bid/Ask*" {
                        $lastBidAsk = $Unencoded.split(" ")[5]
                        $lastBid = $lastBidAsk.Split('/')[0]
                        $lastask = $lastBidAsk.Split('/')[1]
                        $RoundDate=$Unencoded.split(" ")[0]
                        $RoundTime=$Unencoded.split(" ")[1]
                    }
                    "RSI:*" {
                        $RSI = $Unencoded.split(" ")[1]
                    }
                    "*TrailingBuy limit*" {
                        $TrailingBuylimit = $Unencoded.split(" ")[4] 
                    }
                    "Averaged bought price:*" {
                        $AVerageBroughtPrice = $Unencoded.split(" ")[3]
                    }
                    "*GUNBOT CALLBACK*Sell price*" {
                         $SellPrice = $Unencoded.split(" ")[9]
                    }
                    "*BTC/USD Money Flow Index is:*"{
                        $MFI = $Unencoded.split(" ")[5]
                    }
                    "*Safety Switch is on...*" {
                        $Safety = 'On'
                    }
                    "*Entering Buy Cycle*" {
                        $BuyCycle = 'X'
                    }
                    "*Entering Sell Cycle*" {
                        $SellCycle = 'X'
                    }
                    "*Price to buy*" {
                        $PriceToBuy = $Unencoded.split(" ")[5]
                    }
                    "*Strategy Exit Point*" {
                        $ExitPoint =   ($Unencoded.split(" ")[6]).split('/')[1]
                    }
                    "*Strategy Entry Point*" {
                        $EntryPoint =  ($Unencoded.split(" ")[6]).split('/')[1]
                    }
                    "*EMA1*===*EMA2*" {
                        $EMA1 =  $Unencoded.split(" ")[1]
                        $EMA2 =  $Unencoded.split(" ")[4]
                    }
                    "*Processing strategy*"{
                        $strategy =  ($Unencoded.split(" ")[2])
                    }
                    "*HIGH BB*==*SMA:*==* LOW BB*" {
                        $HighBB =  $Unencoded.split(" ")[2]
                        $SMA =  $Unencoded.split(" ")[5]
                        $LowBB =  $Unencoded.split(" ")[9]
                    }
                    "*We averaged down too many times already...(DU_CAP_COUNT)*"{
                        $DUCAP = 'X'
                    }
                    "Gunbot XT says: Trailing Profit limits are still good...waiting to sell..."{
                        $TSSLSellWaiting = 'X'
                    }
                }
            }
            if ($LastPair -ne $Pair)
            {
          
                $PairDataRecord = '' | select 'Date','Time','StartLine','EndLine','Round','GBVersion', 'Exchange', 'Pair','strategy','RSI','LastBid','LastAsk','AverageBroughtPrice','SellPrice','MFI','Safety','SellCycle','CoinDiffPriceToSell','BuyCycle','DUCAP','TSSLSellWaiting','PriceToBuy','ExitPoint','EntryPoint','EMA1','EMA2','HighBB','SMA','LowBB'
                $PairDataRecord.StartLine = $NewPairLine
                $PairDataRecord.EndLine = $i
                $PairDataRecord.GBVersion = $GBVersion
                $PairDataRecord.Exchange = $Exchange
                $PairDataRecord.Pair = $LastPair
                $PairDataRecord.RSI = $RSI
                $PairDataRecord.Round = $Lastround
                $PairDataRecord.LastBid = $lastBid
                $PairDataRecord.LastAsk = $lastAsk
                $PairDataRecord.AverageBroughtPrice = $AverageBroughtPrice
                $PairDataRecord.Date = $RoundDate
                $PairDataRecord.time = $roundTime
                $PairDataRecord.SellPrice = $SellPrice
                $PairDataRecord.MFI = $MFI
                $PairDataRecord.Safety = $Safety
                $PairDataRecord.SellCycle = $SellCycle
                $PairDataRecord.BuyCycle = $BuyCycle
                $PairDataRecord.PriceToBuy = $PriceToBuy
                $PairDataRecord.ExitPoint = $ExitPoint
                $PairDataRecord.EntryPoint = $EntryPoint
                $PairDataRecord.EMA1 = $EMA1
                $PairDataRecord.EMA2 = $EMA2
                $PairDataRecord.strategy = $strategy
                $PairDataRecord.HighBB = $HighBB
                $PairDataRecord.SMA = $SMA
                $PairDataRecord.LowBB = $LowBB
                $PairDataRecord.DUCAP = $DUCAP
                $PairDataRecord.TSSLSellWaiting = $TSSLSellWaiting
                $PairDataRecord.CoinDiffPriceToSell = $PairDataRecord.LastBid - $PairDataRecord.SellPrice 
                
                if ($LastPair -eq $null) {
                    $lastpair = $pair
                    $LastExchange = $Exchange
                    $LastPairLogs = $PairLogs
                    $LastPairDataRecord = $PairDataRecord 
                }
                $LastPairDataRecord = $PairDataRecord 
                $CSVData = join-path $LastPairLogs "Data\$($LastExchange.Substring(0,3).toupper())_$($LastPair)_Data.csv"
                $PairDataRecord | Export-Csv -Append -Path $CSVData -NoTypeInformation 
                $PairDataRecord | Export-Csv -Append -Path $ExchangeCSVData  -NoTypeInformation 
                $SellPrice='';$roundTime='';$RoundDate='';$AverageBroughtPrice='';$lastAsk='';$lastBid='';$RSI='';$MFI='';$Safety='';$BuyCycle='';$SellCycle='';$PriceToBuy='';$EntryPoint='';$ExitPoint='';$EMA1='';$EMA2='';$strategy='';$HighBB='';$SMA='';$LowBB='';$DUCAP='';$TSSLSellWaiting='';$CoinDiffPriceToSell=''
                $NewPairLine=$i
                $CurrentPlace.Name = $GBLogName
                $CurrentPlace.CreateDate = $CurrentLogFile.CreationTimeUTC
                $CurrentPlace.LineText = clean-code $Line
                $CurrentPlace.LastParsedLine = $i -1
                $CurrentPlace | ConvertTo-Json | Out-File $LastLog -Force
            }

       
            if ($Lastround -ne $round) 
            {
                if ($i -lt $TotalLines) 
                {
                    cls
                    write-host 'Catching up.....' -ForegroundColor Gray
                    $Percent =  "{0:N0}" -f ($i / $TotalLines * 100)
                    write-host "Line: `t$i of $TotalLines ($Percent%)`n`n`n`n`n`n"  -ForegroundColor Gray
                    Write-Progress -PercentComplete $Percent -Activity "Catching up on existing $GBLogName Entries" -Status "Processing..." 
                    Get-Art;Get-Beer
                } 
                else
                {
                    Write-Progress -Completed -Activity "Catching up on existing"
                    #$OGV = $PairRoundStatistics | Out-GridView -PassThru
                    cls;Get-Art;Get-Beer
                    write-host "******Live******" -ForegroundColor DarkGreen
                    write-host "Line: `t$i" -ForegroundColor Gray
                    write-host "Round: `t$round " -ForegroundColor Gray
                    $NumberOfPairs = $P
                    write-host "Pairs: `t$NumberOfPairs " -ForegroundColor Gray
                    write-host "****************`n" -ForegroundColor DarkGreen
                    write-host "Pair `t`tRSI `tBuy `tSell `tDiff to Enter/Exit" -ForegroundColor cyan
                    foreach ($status in $PairRoundStatistics) 
                    {
                        write-host  "$($status.Pair) `t$(("{0:N1}" -f [float]$status.RSI)) `t $($status.BuyCycle) `t $($status.SellCycle) `t $("{0:N8}" -f $status.CoinDiffPriceToSell)" -ForegroundColor Gray
                    }
                    write-host ''
                    $P=0
                    $PairRoundStatistics = @()
                }
            }

            if ($i -gt $TotalLines) 
            {
                if ($Lastpair -ne $pair) 
                {
                        $PairRoundStatistics += $PairDataRecord
                        write-host '.' -NoNewline -ForegroundColor DarkYellow
                        #write-host "$($PairDataRecord.Pair) `t $("{0:N1}" -f $PairDataRecord.RSI) `t $($PairDataRecord.BuyCycle) `t $($PairDataRecord.SellCycle) `t $("{0:N8}" -f $PairDataRecord.CoinDiffPriceToSell)" -ForegroundColor Gray
                        $P++
                }
            }

            $LastLine = $line
            $LastPairLogs = $PairLogs
            $LastPair = $Pair
            $Lastround = $round
            $PairDataRecord = $null
            $LastExchange = $Exchange       
        }
        $i++
    }
}
function Get-Art {
    Param(
        $time =$False,
        $sleep=$false
    )
 
    Write-host ''
    Write-host ' .88888. 88888ba dP .d8888b dP' -NoNewline -ForegroundColor Cyan;Write-Host ' oo ' -ForegroundColor Magenta -NoNewline ;write-host ' dP dP '-ForegroundColor Cyan
    Write-host 'd8 88 88 8b 88 88. " 88 88 88 ' -ForegroundColor DarkCyan
    Write-host '88 a88aaa8P 88 .d8888b. .d8888b. Y8888b. 88d88b. 88 dP d8888P d8888P .d888b. 88d88b. ' -ForegroundColor DarkGreen
    Write-host '88 YP88 88 8b. 88 88 88 88 88 8b 88 88 88 88 88 88 88oood8 88 88 ' -ForegroundColor Green
    Write-host 'Y8. .88 88 .88 88 88. .88 88. .88 d8 .8P 88. .88 88 88 88 88 88. ... 88 ' -ForegroundColor Yellow
    Write-host '`88888 8888888P 88888P 88888P 8888P88 Y8888P 88Y88P dP dP dP dP 8888P dP ' -ForegroundColor DarkGray
    Write-host ' .88 88 ' -ForegroundColor Magenta
    Write-host " d8888P dP `n" -ForegroundColor gray;if($sleep){sleep 1}
    if ($time) {Write-host "`n`nThis shit does take time, if this helps you,";sleep 2;write-host "`nhelp me, help you... " -nonewline;sleep 2;write-host "consider shouting me a beer or two`n`n";sleep 2}
}

Function Get-Beer {
    Write-host "`nDonations / Beer Fund`n" -ForegroundColor Gray
    Write-host "BTC: 32qxmEDf5bZnU1jHe3CgejFZBNbaaoxZy6"
    Write-host "ETH: 0x2c871de231928337cab4b78bc5a09af8c3738757"
    Write-host "LTC: LeViymW3KRnda2ncVRqqpn14cQjDyoKakZ`n"
    Write-host "`nSource Code / Contribute / Issues / Updates / Requests " -ForegroundColor Gray
    Write-host "https://github.com/lucidqdreams/GBLogSplitter`n" -ForegroundColor Cyan
}