diff --git a/cabal.project b/cabal.project index 679264f7..d0408daa 100644 --- a/cabal.project +++ b/cabal.project @@ -27,7 +27,6 @@ packages: src/dex/muesli/muesli-core src/dex/muesli/muesli-node-client src/node-client - src/trading-bot src/wallet src/un-ada diff --git a/changelog.md b/changelog.md index ffa4c40c..b5c142df 100644 --- a/changelog.md +++ b/changelog.md @@ -27,6 +27,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * Add `utcTimeToPosixTime` in `Convex.Utils`. * Considering explicit error type `MonadBlockchainError` for `MonadBlockchainCardanoNodeT` to enable proper error handling by caller. +### Deleted + +* Deleted the `trading-bot` package. + ## [0.0.1] - 2023-04-26 * Initial release diff --git a/src/base/lib/Convex/Class.hs b/src/base/lib/Convex/Class.hs index a15a2a99..ba40baba 100644 --- a/src/base/lib/Convex/Class.hs +++ b/src/base/lib/Convex/Class.hs @@ -199,7 +199,7 @@ data MonadBlockchainError e = instance Show e => Show (MonadBlockchainError e) where show (MonadBlockchainError e) = show e - show (FailWith str) = str + show (FailWith str) = str {-| 'MonadBlockchain' implementation that connects to a cardano node -} diff --git a/src/devnet/lib/Convex/Devnet/CardanoNode.hs b/src/devnet/lib/Convex/Devnet/CardanoNode.hs index b917b6ed..9017879e 100644 --- a/src/devnet/lib/Convex/Devnet/CardanoNode.hs +++ b/src/devnet/lib/Convex/Devnet/CardanoNode.hs @@ -35,8 +35,7 @@ import Control.Tracer (Tracer, traceWith) import qualified Convex.Devnet.NodeQueries as Q import Convex.Devnet.Utils (checkProcessHasNotDied, defaultNetworkId, failure, - readConfigFile, - withLogFile) + readConfigFile, withLogFile) import Data.Aeson (FromJSON, ToJSON (toJSON), (.=)) import qualified Data.Aeson as Aeson import qualified Data.Aeson.KeyMap as Aeson.KeyMap @@ -165,7 +164,7 @@ withCardanoNode tr networkId stateDirectory args@CardanoNodeArgs{nodeSocket, nod (checkProcessHasNotDied "cardano-node" processHandle) waitForNode `finally` cleanupSocketFile >>= \case - Left _ -> failure "withCardanoNode: unexpected termination" + Left _ -> failure "withCardanoNode: unexpected termination" Right res -> pure res where diff --git a/src/devnet/lib/Convex/Devnet/Wallet.hs b/src/devnet/lib/Convex/Devnet/Wallet.hs index 9a549430..71feee13 100644 --- a/src/devnet/lib/Convex/Devnet/Wallet.hs +++ b/src/devnet/lib/Convex/Devnet/Wallet.hs @@ -22,31 +22,31 @@ module Convex.Devnet.Wallet( runningNodeBlockchain ) where -import Cardano.Api (AddressInEra, BabbageEra, BuildTx, - Lovelace, Tx, TxBodyContent) -import qualified Cardano.Api as C -import Control.Monad.IO.Class (MonadIO (..)) -import Control.Monad.Reader (ReaderT (..), ask, lift) -import Control.Tracer (Tracer, traceWith) -import qualified Convex.BuildTx as BuildTx -import Convex.Class (MonadBlockchain, - runMonadBlockchainCardanoNodeT, - sendTx) -import qualified Convex.CoinSelection as CoinSelection -import Convex.Devnet.CardanoNode (RunningNode (..)) -import qualified Convex.Devnet.NodeQueries as NodeQueries -import Convex.Devnet.Utils (keysFor) -import Convex.Lenses (emptyTx) -import Convex.MonadLog (MonadLog (..)) -import Convex.Utxos (UtxoSet) -import qualified Convex.Utxos as Utxos -import Convex.Wallet (Wallet (..), address) -import qualified Convex.Wallet as Wallet -import Data.Aeson (FromJSON, ToJSON) -import Data.Function ((&)) -import Data.Text (Text) -import GHC.Generics (Generic) -import Prettyprinter (defaultLayoutOptions, layoutPretty) +import Cardano.Api (AddressInEra, BabbageEra, BuildTx, + Lovelace, Tx, TxBodyContent) +import qualified Cardano.Api as C +import Control.Monad.IO.Class (MonadIO (..)) +import Control.Monad.Reader (ReaderT (..), ask, lift) +import Control.Tracer (Tracer, traceWith) +import qualified Convex.BuildTx as BuildTx +import Convex.Class (MonadBlockchain, + runMonadBlockchainCardanoNodeT, + sendTx) +import qualified Convex.CoinSelection as CoinSelection +import Convex.Devnet.CardanoNode (RunningNode (..)) +import qualified Convex.Devnet.NodeQueries as NodeQueries +import Convex.Devnet.Utils (keysFor) +import Convex.Lenses (emptyTx) +import Convex.MonadLog (MonadLog (..)) +import Convex.Utxos (UtxoSet) +import qualified Convex.Utxos as Utxos +import Convex.Wallet (Wallet (..), address) +import qualified Convex.Wallet as Wallet +import Data.Aeson (FromJSON, ToJSON) +import Data.Function ((&)) +import Data.Text (Text) +import GHC.Generics (Generic) +import Prettyprinter (defaultLayoutOptions, layoutPretty) import qualified Prettyprinter.Render.Text as Render faucet :: IO Wallet diff --git a/src/trading-bot/LICENSE b/src/trading-bot/LICENSE deleted file mode 100644 index 0c8a8002..00000000 --- a/src/trading-bot/LICENSE +++ /dev/null @@ -1,53 +0,0 @@ -Apache License - -Version 2.0, January 2004 - -http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. - -"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: - -You must give any other recipients of the Work or Derivative Works a copy of this License; and -You must cause any modified files to carry prominent notices stating that You changed the files; and -You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and -If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. - -You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. -5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS diff --git a/src/trading-bot/app/Main.hs b/src/trading-bot/app/Main.hs deleted file mode 100644 index ba3ca68d..00000000 --- a/src/trading-bot/app/Main.hs +++ /dev/null @@ -1,6 +0,0 @@ -module Main where - -import Convex.TradingBot.Cli (runMain) - -main :: IO () -main = runMain diff --git a/src/trading-bot/convex-trading-bot.cabal b/src/trading-bot/convex-trading-bot.cabal deleted file mode 100644 index f4de2d77..00000000 --- a/src/trading-bot/convex-trading-bot.cabal +++ /dev/null @@ -1,87 +0,0 @@ -cabal-version: 3.0 -name: convex-trading-bot -version: 0.0.1 -synopsis: Trading bot -license: Apache-2.0 -license-files: - LICENSE - -maintainer: j-mueller@users.noreply.github.com -author: Jann Müller -homepage: https://github.com/j-mueller/sc-tools -bug-reports: https://github.com/j-mueller/sc-tools -description: - Please see the README on GitHub at - -build-type: Simple - -common lang - default-language: Haskell2010 - default-extensions: ExplicitForAll ScopedTypeVariables MultiParamTypeClasses - DeriveGeneric StandaloneDeriving DeriveLift FlexibleContexts - GeneralizedNewtypeDeriving DeriveFunctor DeriveFoldable - DeriveTraversable ImportQualifiedPost NumericUnderscores - ghc-options: -Wall -Wnoncanonical-monad-instances -Wunused-packages - -Wincomplete-uni-patterns -Wincomplete-record-updates - -Wredundant-constraints -Widentities - -library - import: lang - exposed-modules: - Convex.TradingBot - Convex.TradingBot.Annealing - Convex.TradingBot.Cli.Command - Convex.TradingBot.Cli.Config - Convex.TradingBot.Cli - Convex.TradingBot.LPPoolEvent - Convex.TradingBot.NodeClient - Convex.TradingBot.NodeClient.BacktestingClient - Convex.TradingBot.NodeClient.OrderClient - Convex.TradingBot.NodeClient.PricesClient - Convex.TradingBot.NodeClient.TradingClient - Convex.TradingBot.Portfolio - Convex.TradingBot.Prices - Convex.TradingBot.Rules - Convex.TradingBot.Stats - hs-source-dirs: lib - build-depends: - base >= 4.14.0, - text, - containers, - lens, - convex-base, - convex-node-client, - convex-wallet, - convex-muesli-core, - convex-coin-selection, - transformers, - optparse-applicative, - mtl, - fingertree, - strict-containers, - katip, - stm, - streaming, - mwc-probability, - annealing, - primitive, - deepseq, - csv, - streaming-cassava, - streaming-with, - cassava - - -- cardano dependencies - build-depends: - cardano-api - -executable convex-trading-bot - import: lang - main-is: Main.hs - build-depends: - base ^>=4.14.3.0, - convex-trading-bot - hs-source-dirs: app - default-language: Haskell2010 - ghc-options: - -threaded -rtsopts -O2 \ No newline at end of file diff --git a/src/trading-bot/lib/Convex/TradingBot.hs b/src/trading-bot/lib/Convex/TradingBot.hs deleted file mode 100644 index 4eb1924a..00000000 --- a/src/trading-bot/lib/Convex/TradingBot.hs +++ /dev/null @@ -1 +0,0 @@ -module Convex.TradingBot() where diff --git a/src/trading-bot/lib/Convex/TradingBot/Annealing.hs b/src/trading-bot/lib/Convex/TradingBot/Annealing.hs deleted file mode 100644 index 3c65b9bc..00000000 --- a/src/trading-bot/lib/Convex/TradingBot/Annealing.hs +++ /dev/null @@ -1,210 +0,0 @@ -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE DeriveAnyClass #-} -{-# LANGUAGE DerivingStrategies #-} -{-# LANGUAGE NamedFieldPuns #-} -{-# LANGUAGE NumericUnderscores #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE RankNTypes #-} -{-# LANGUAGE ScopedTypeVariables #-} -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE TypeApplications #-} -{-# LANGUAGE ViewPatterns #-} -{-| Using simulated annealing to find a good set of trading rules --} -module Convex.TradingBot.Annealing( - runBacktestNode, - optimiseRules, - runAnnealing -) where - -import Annealing (AnnealingState (..), - AssessedCandidate (..), - annealing) -import Cardano.Api (AssetName, Lovelace, - PolicyId, Quantity) -import qualified Cardano.Api as C -import qualified Control.Concurrent.STM as STM -import Control.Exception (bracket) -import Control.Lens (Lens', anon, at, - makeLenses, use, - (%=)) -import Control.Monad (void, when) -import Control.Monad.IO.Class (MonadIO (..)) -import Control.Monad.Primitive (PrimMonad, - PrimState) -import Control.Monad.State.Strict (evalStateT) -import Control.Monad.Trans.Class (lift) -import Control.Monad.Trans.Except (ExceptT (..), - runExceptT) -import Convex.MonadLog (MonadLog, - MonadLogIgnoreT (..), - MonadLogKatipT (..), - logInfoS, logWarnS) -import Convex.NodeClient.Types (runNodeClient) -import qualified Convex.TradingBot.NodeClient as NC -import Convex.TradingBot.NodeClient.PricesClient (PriceEventRow (..)) -import Convex.TradingBot.Portfolio (Portfolio, - PortfolioConfig (..)) -import qualified Convex.TradingBot.Portfolio as Portfolio -import Convex.TradingBot.Prices (LPPrices) -import qualified Convex.TradingBot.Prices as Prices -import Convex.TradingBot.Rules (Rule, - SearchableRule (..)) -import qualified Convex.TradingBot.Rules as Rules -import Convex.Wallet.Cli.Config (Config (..), - ConfigMode (..)) -import Data.Foldable (traverse_) -import Data.Map.Strict (Map) -import qualified Data.Map.Strict as Map -import Data.Maybe (fromMaybe) -import qualified Data.Text as Text -import qualified Katip as K -import qualified Streaming -import Streaming (Of, Stream) -import Streaming.Cassava (CsvParseException, - decodeByNameWith, - defaultDecodeOptions) -import qualified Streaming.Prelude as S -import Streaming.With (MonadMask, - withBinaryFileContents) -import System.Exit (exitFailure) -import System.IO (stdout) -import qualified System.Random.MWC.Probability as P -import System.Random.MWC.Probability (Gen) - -data Prices = - Prices - { _priceHistory :: !(Map (PolicyId, AssetName) LPPrices) - , _lastPrices :: !(Map (PolicyId, AssetName) (Lovelace, Quantity)) - } - -makeLenses ''Prices - -runBacktestNode :: (MonadLog m, MonadIO m) => Rule -> K.LogEnv -> Config 'Typed -> m (Portfolio, C.Value) -runBacktestNode rule logEnv Config{cardanoNodeConfigFile, cardanoNodeSocket} = do - logInfoS "Starting backtest" - tv <- liftIO STM.newEmptyTMVarIO - result <- liftIO $ do - let makeLogEnv = do - backtestingWorkerScribe <- K.mkHandleScribe (K.ColorLog True) stdout (K.permitItem K.NoticeS) K.V2 - K.registerScribe "stdout-backtesting-worker" backtestingWorkerScribe K.defaultScribeSettings logEnv - bracket makeLogEnv K.closeScribes $ \le -> - let client C.LocalNodeConnectInfo{C.localNodeNetworkId} env = do - pure (NC.backtestingClient rule tv le "backtesting" localNodeNetworkId env) - in runExceptT (runNodeClient cardanoNodeConfigFile cardanoNodeSocket client) - case result of - Left err -> do - logWarnS (Text.unpack $ C.renderInitialLedgerStateError err) - liftIO exitFailure - Right () -> do - logInfoS "Backtesting finished" - liftIO (STM.atomically (STM.takeTMVar tv)) - -runBacktest :: (MonadIO m, MonadMask m, MonadLog m, SearchableRule r) => PortfolioConfig -> Lovelace -> FilePath -> r -> (ExceptT CsvParseException m) (Portfolio, C.Value) -runBacktest config initialAda fp rule = - let options = defaultDecodeOptions - in withBinaryFileContents fp - $ evalPriceEvents config initialAda rule - . decodeByNameWith options - -pricesFor :: (PolicyId, AssetName) -> Lens' Prices LPPrices -pricesFor k = priceHistory . at k . anon Prices.empty Prices.null - -evalPriceEvents :: (SearchableRule r, Monad m, MonadLog m) => PortfolioConfig -> Lovelace -> r -> Stream (Of PriceEventRow) m () -> m (Portfolio, C.Value) -evalPriceEvents config initialAda (signal -> rule) stream = do - let portf = (Portfolio.emptyPortfolio, C.lovelaceToValue initialAda) - init_ :: Prices - init_ = Prices mempty mempty - flip evalStateT init_ $ Portfolio.execSimulatedPortfolioT config portf $ Portfolio.runLoggingPortfolioT $ do - flip S.mapM_ (Streaming.hoist (lift . lift . lift) stream) $ \PriceEventRow{peBlockNo, peSlot, pePolicyId, peAssetName, peQuantity, peLovelace} -> do - let k = (pePolicyId, peAssetName) - newPrice = (peLovelace, peQuantity) - oldPrices <- use lastPrices - let oldPrice = Map.findWithDefault (0, 0) k oldPrices - pAt = Prices.pricesAt peBlockNo peSlot oldPrice newPrice - p = fromMaybe mempty $ Prices.price $ Prices._stats pAt - when (Prices.pmVolume p > 0) $ do - pricesFor k %= Prices.prepend pAt - newPrices' <- use (pricesFor k) - let pricePoint = (pePolicyId, peAssetName, peQuantity, peLovelace) - void (Portfolio.update pricePoint) - case rule newPrices' of - Rules.Buy -> void (Portfolio.buy 1.0 pricePoint) - Rules.Sell -> void (Portfolio.sell 1.0 pricePoint) - _ -> pure () - -{-| Evaluate the rule against the price events in the CSV file --} -evaluateRuleL :: SearchableRule r => Lovelace -> FilePath -> K.LogEnv -> r -> PortfolioConfig -> IO (Portfolio, C.Value) -evaluateRuleL initialAda csvFile logEnv rule config = K.runKatipContextT logEnv () "test-rule" $ runMonadLogKatipT $ do - runExceptT (runBacktest config initialAda csvFile rule) >>= either (error . show) pure - -{-| Evaluate the rule against the price events in the CSV file --} -evaluateRuleNL :: SearchableRule r => Lovelace -> FilePath -> r -> PortfolioConfig -> IO (Portfolio, C.Value) -evaluateRuleNL initialAda csvFile rule config = runMonadLogIgnoreT $ do - runExceptT (runBacktest config initialAda csvFile rule) >>= either (error . show) pure - -fitness :: (Portfolio, C.Value) -> Double -fitness (portfolio, vl) = - let C.Lovelace totalVal = Portfolio.aum vl portfolio - in if (totalVal /= 0) - then (1 / fromIntegral totalVal) - else 1 - -optimiseRules :: forall r m. - (SearchableRule r, MonadIO m) => - r -> - FilePath -> - K.LogEnv -> - m ( Stream (Of (AnnealingState (AssessedCandidate (r, PortfolioConfig) (Portfolio, C.Value)))) IO () - , AssessedCandidate (r, PortfolioConfig) (Portfolio, C.Value) - , Lovelace - ) -optimiseRules i fp logEnv = do - gen <- liftIO P.createSystemRandom - let initialAda = 3_000_000_000 - config = Portfolio.defaultPortfolioConfig - initial <- liftIO (evaluateRuleL initialAda fp logEnv i config) - let temp j = 1 + (1 / fromIntegral j) - cand = AssessedCandidate (i, config) initial (fitness initial) - stream = - annealing - gen - temp - (uncurry (evaluateRuleNL initialAda fp)) - fitness - cand - (\(r, cfg) -> (,) <$> neighbours gen r <*> searchPortfolioConfig gen cfg) - return (stream, cand, initialAda) - -runAnnealing :: (MonadIO m, MonadLog m) => K.LogEnv -> FilePath -> m () -runAnnealing logEnv filePath = do - logInfoS "Starting annealing" - let r = Rules.twoMovingAverages - -- let r = Rules.movingAverages - (stream, initialRule, C.Lovelace initialAda) <- optimiseRules r filePath logEnv - result <- liftIO (S.last_ (S.take 2_000 stream)) - flip traverse_ result $ \AnnealingState{asBestCandidate, asCurrentCandidate} -> do - let p (AssessedCandidate{acCandidate, acResult=(pf, v)}) = do - logInfoS (show acCandidate) - let C.Lovelace currentVal = Portfolio.aum v pf - diff = currentVal - initialAda - percent = (100 :: Double) * (fromIntegral diff / fromIntegral initialAda) - Portfolio.printPortfolioInfo v pf - logInfoS $ "Value change: " <> show percent <> "%" - logInfoS "Initial value:" - p initialRule - - logInfoS $ "Best result:" - p asBestCandidate - - logInfoS $ "Current result:" - p asCurrentCandidate - -searchPortfolioConfig :: (PrimMonad m) => Gen (PrimState m) -> PortfolioConfig -> m PortfolioConfig -searchPortfolioConfig gen cfg = do - let sv = 0.05 - stopLoss <- max 0.1 . (\i -> toRational (1000 * i) / 1000) <$> P.sample (P.normal (fromRational $ pfDefaultStopLoss cfg) sv) gen - defLimit <- max 0.1 . (\i -> toRational (1000 * i) / 1000) <$> P.sample (P.normal (fromRational $ pfDefaultLimit cfg) sv) gen - pure cfg{pfDefaultStopLoss = stopLoss, pfDefaultLimit = defLimit} diff --git a/src/trading-bot/lib/Convex/TradingBot/Cli.hs b/src/trading-bot/lib/Convex/TradingBot/Cli.hs deleted file mode 100644 index 62114c59..00000000 --- a/src/trading-bot/lib/Convex/TradingBot/Cli.hs +++ /dev/null @@ -1,119 +0,0 @@ -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE NamedFieldPuns #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE TypeApplications #-} -module Convex.TradingBot.Cli (runMain) where - -import qualified Cardano.Api as C -import Control.Exception (bracket) -import Control.Monad.Except (MonadError (..)) -import Control.Monad.IO.Class (MonadIO (..)) -import Control.Monad.Trans.Except (runExceptT) -import Convex.MonadLog (MonadLog, - MonadLogKatipT (..), - logInfoS, logWarnS) -import Convex.NodeClient.Types (runNodeClient) -import Convex.NodeQueries (loadConnectInfo) -import Convex.TradingBot.Annealing (runAnnealing) -import Convex.TradingBot.Cli.Command (CliCommand (..), - commandParser) -import Convex.TradingBot.Cli.Config (Order (..)) -import qualified Convex.TradingBot.NodeClient as NC -import Convex.TradingBot.NodeClient.PricesClient (PriceEventRow) -import qualified Convex.TradingBot.Rules as Rules -import Convex.Wallet.Cli.Config (Config (..), - ConfigMode (..), - ParseFields (..)) -import Data.CSV.Export (defaultCSVConfig, - writeCSVHeader) -import Data.Proxy (Proxy (..)) -import qualified Data.Text as Text -import qualified Katip as K -import Options.Applicative (customExecParser, - disambiguate, - helper, idm, info, - prefs, - showHelpOnEmpty, - showHelpOnError) -import System.Exit (exitFailure) -import qualified System.IO as IO -import System.IO (stdout) - -runMain :: IO () -runMain = do - mainScribe <- K.mkHandleScribe (K.ColorLog True) stdout (K.permitItem K.InfoS) K.V2 - initLogEnv <- K.initLogEnv "trading-bot" "cli" - let makeLogEnv = K.registerScribe "stdout-main" mainScribe K.defaultScribeSettings initLogEnv - bracket makeLogEnv K.closeScribes $ \le -> K.runKatipContextT le () "main" $ runMonadLogKatipT $ do - command <- liftIO (customExecParser - (prefs $ disambiguate <> showHelpOnEmpty <> showHelpOnError) - (info (helper <*> commandParser) idm)) - result <- runExceptT $ do - case command of - StartTrading config -> - mkTyped config >>= startTrading le - Buy config order -> - (,) <$> mkTyped config <*> mkTyped order >>= uncurry (executeBuyOrder le) - Sell config order -> - (,) <$> mkTyped config <*> mkTyped order >>= uncurry (executeSellOrder le) - Optimise fp -> runAnnealing le fp - ExportPrices config outFile -> - mkTyped config >>= runExport le outFile - case result of - Left err -> do - logWarnS "Error in runMain" - logWarnS (Text.unpack $ C.renderInitialLedgerStateError err) - Right () -> pure () - -startTrading :: (MonadLog m, MonadError C.InitialLedgerStateError m, MonadIO m) => K.LogEnv -> Config 'Typed -> m () -startTrading logEnv Config{cardanoNodeConfigFile, cardanoNodeSocket, wallet} = do - (info_, _) <- loadConnectInfo cardanoNodeConfigFile cardanoNodeSocket - let client _ env = do - pure (NC.tradingClient (Rules.signal Rules.twoMovingAverages) logEnv "trading" wallet (C.localNodeNetworkId info_) env) - logInfoS "Starting the trading bot" - result <- liftIO $ runExceptT (runNodeClient cardanoNodeConfigFile cardanoNodeSocket client) - case result of - Left err -> throwError err - Right () -> pure () - -executeBuyOrder :: (MonadLog m, MonadError C.InitialLedgerStateError m, MonadIO m) => K.LogEnv -> Config 'Typed -> Order 'Typed -> m () -executeBuyOrder logEnv Config{cardanoNodeConfigFile, cardanoNodeSocket, wallet} order = do - (info_, _) <- loadConnectInfo cardanoNodeConfigFile cardanoNodeSocket - let client _ env = do - pure (NC.buyOrderClient info_ logEnv "order" wallet order env) - logInfoS "Processing BUY order" - result <- liftIO $ runExceptT (runNodeClient cardanoNodeConfigFile cardanoNodeSocket client) - case result of - Left err -> throwError err - Right () -> pure () - -executeSellOrder :: (MonadLog m, MonadError C.InitialLedgerStateError m, MonadIO m) => K.LogEnv -> Config 'Typed -> Order 'Typed -> m () -executeSellOrder logEnv Config{cardanoNodeConfigFile, cardanoNodeSocket, wallet} order = do - (info_, _) <- loadConnectInfo cardanoNodeConfigFile cardanoNodeSocket - let client _ env = do - pure (NC.sellOrderClient info_ logEnv "order" wallet order env) - logInfoS "Processing SELL order" - result <- liftIO $ runExceptT (runNodeClient cardanoNodeConfigFile cardanoNodeSocket client) - case result of - Left err -> throwError err - Right () -> pure () - -runExport :: (MonadError C.InitialLedgerStateError m, MonadIO m) => K.LogEnv -> FilePath -> Config 'Typed -> m () -runExport logEnv fp Config{cardanoNodeConfigFile, cardanoNodeSocket} = do - (info_, _) <- loadConnectInfo cardanoNodeConfigFile cardanoNodeSocket - let client handle _ env = do - pure (NC.pricesClient handle (C.localNodeNetworkId info_) logEnv "prices" env) - result <- liftIO $ do - IO.withFile fp IO.WriteMode $ \handle -> do - writeCSVHeader handle defaultCSVConfig (Proxy @PriceEventRow) - runExceptT (runNodeClient cardanoNodeConfigFile cardanoNodeSocket (client handle)) - case result of - Left err -> throwError err - Right () -> pure () - -mkTyped :: (ParseFields c, MonadIO m, MonadLog m) => c 'Str -> m (c 'Typed) -mkTyped c = case parseFields c of - Left err -> do - logWarnS (show err) - liftIO exitFailure - Right k -> pure k diff --git a/src/trading-bot/lib/Convex/TradingBot/Cli/Command.hs b/src/trading-bot/lib/Convex/TradingBot/Cli/Command.hs deleted file mode 100644 index 46875e03..00000000 --- a/src/trading-bot/lib/Convex/TradingBot/Cli/Command.hs +++ /dev/null @@ -1,52 +0,0 @@ -{-# LANGUAGE DataKinds #-} -{-| --} -module Convex.TradingBot.Cli.Command( - CliCommand(..), - commandParser - ) where - -import Convex.TradingBot.Cli.Config (Order, orderParser) -import Convex.Wallet.Cli.Config (Config, ConfigMode (..), - configParser) -import Options.Applicative (CommandFields, Mod, Parser, - command, fullDesc, help, info, - long, progDesc, strOption, - subparser) -data CliCommand = - StartTrading (Config 'Str) - | Buy (Config 'Str) (Order 'Str) - | Sell (Config 'Str) (Order 'Str) - | Optimise FilePath - | ExportPrices (Config 'Str) FilePath - -commandParser :: Parser CliCommand -commandParser = - subparser $ - mconcat - [ startTrading - , buy - , sell - , optimise - , exportPrices - ] - -startTrading :: Mod CommandFields CliCommand -startTrading = command "start-trading" $ - info (StartTrading <$> configParser) (fullDesc <> progDesc "Start the trading bot") - -buy :: Mod CommandFields CliCommand -buy = command "buy" $ - info (Buy <$> configParser <*> orderParser) (fullDesc <> progDesc "Buy assets on MuesliSwap") - -sell :: Mod CommandFields CliCommand -sell = command "sell" $ - info (Sell <$> configParser <*> orderParser) (fullDesc <> progDesc "Sell assets on MuesliSwap") - -optimise :: Mod CommandFields CliCommand -optimise = command "optimise" $ - info (Optimise <$> strOption (long "prices" <> help "CSV file for the prices")) (fullDesc <> progDesc "Use the annealing algorithm to optimise a set of trading rules") - -exportPrices :: Mod CommandFields CliCommand -exportPrices = command "export-prices" $ - info (ExportPrices <$> configParser <*> strOption (long "out" <> help "CSV file for the prices")) (fullDesc <> progDesc "Export the price history to CSV") diff --git a/src/trading-bot/lib/Convex/TradingBot/Cli/Config.hs b/src/trading-bot/lib/Convex/TradingBot/Cli/Config.hs deleted file mode 100644 index 341dfdd0..00000000 --- a/src/trading-bot/lib/Convex/TradingBot/Cli/Config.hs +++ /dev/null @@ -1,48 +0,0 @@ -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE DerivingStrategies #-} -{-# LANGUAGE FlexibleInstances #-} -{-# LANGUAGE NamedFieldPuns #-} -{-# LANGUAGE TypeFamilies #-} -{-| --} -module Convex.TradingBot.Cli.Config( - Order(..), - orderParser -) where - -import Cardano.Api (AssetName, Lovelace, PolicyId, - Quantity) -import qualified Cardano.Api as C -import Convex.Wallet.Cli.Config (ConfigField, ConfigMode (..), - ParseField (..), ParseFields (..)) -import Options.Applicative (Parser, auto, help, long, option, - strOption) - -data Order (m :: ConfigMode) = - Order - { policyId :: ConfigField m PolicyId - , assetName :: ConfigField m AssetName - , quantity :: Quantity - , lovelace :: Lovelace - } - -deriving stock instance Eq (Order 'Str) -deriving stock instance Ord (Order 'Str) -deriving stock instance Show (Order 'Str) -deriving stock instance Show (Order 'Typed) - -orderParser :: Parser (Order 'Str) -orderParser = - Order - <$> strOption (long "policy-id" <> help "Policy ID (hex) of the native currency") - <*> strOption (long "asset-name" <> help "Asset name (hex) of the native currency") - <*> fmap C.Quantity (option auto (long "quantity" <> help "Amount of units of the native currency")) - <*> fmap C.Lovelace (option auto (long "lovelace" <> help "Price in lovelace")) - -instance ParseFields Order where - parseFields Order{policyId, assetName, quantity, lovelace} = - Order - <$> parseField policyId - <*> parseField assetName - <*> pure quantity - <*> pure lovelace diff --git a/src/trading-bot/lib/Convex/TradingBot/LPPoolEvent.hs b/src/trading-bot/lib/Convex/TradingBot/LPPoolEvent.hs deleted file mode 100644 index fe030ea6..00000000 --- a/src/trading-bot/lib/Convex/TradingBot/LPPoolEvent.hs +++ /dev/null @@ -1,34 +0,0 @@ -{-# LANGUAGE NamedFieldPuns #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE ViewPatterns #-} -module Convex.TradingBot.LPPoolEvent( - LPPoolEvent(..), - OrderbookEvent(..), - extract -) where - -import Cardano.Api (AssetName, Lovelace, PolicyId, - Quantity, ScriptHash) -import qualified Cardano.Api.Shelley as C -import qualified Convex.Muesli.LP.Constants as Muesli -import qualified Convex.Muesli.LP.Types as Muesli - -data LPPoolEvent = - LPPoolEvent - { lpePolicyId :: !PolicyId - , lpeAssetName :: !AssetName - , lpeLovelace :: !Lovelace - , lpeNativeTokenAmount :: !Quantity - } - -data OrderbookEvent = OrderbookEvent - -extract :: C.TxOut C.CtxTx C.BabbageEra -> ScriptHash -> Maybe (Either LPPoolEvent OrderbookEvent) -extract out sh = case Muesli.getPoolScript out sh of - Just (Right (Muesli.adaPair -> Just (lpePolicyId, lpeAssetName), Just (lpeLovelace, lpeNativeTokenAmount))) -> - Just (Left LPPoolEvent{lpePolicyId, lpeAssetName, lpeLovelace, lpeNativeTokenAmount}) - _ | sh == orderbookScriptHash -> Just (Right OrderbookEvent) - | otherwise -> Nothing - -orderbookScriptHash :: C.ScriptHash -orderbookScriptHash = "00fb107bfbd51b3a5638867d3688e986ba38ff34fb738f5bd42b20d5" diff --git a/src/trading-bot/lib/Convex/TradingBot/NodeClient.hs b/src/trading-bot/lib/Convex/TradingBot/NodeClient.hs deleted file mode 100644 index 133fb42e..00000000 --- a/src/trading-bot/lib/Convex/TradingBot/NodeClient.hs +++ /dev/null @@ -1,19 +0,0 @@ -{-# LANGUAGE LambdaCase #-} -{-# LANGUAGE NamedFieldPuns #-} -{-# LANGUAGE NumericUnderscores #-} -{-# LANGUAGE RankNTypes #-} -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE TypeApplications #-} -module Convex.TradingBot.NodeClient( - backtestingClient, - buyOrderClient, - sellOrderClient, - pricesClient, - tradingClient - ) where - -import Convex.TradingBot.NodeClient.BacktestingClient (backtestingClient) -import Convex.TradingBot.NodeClient.OrderClient (buyOrderClient, - sellOrderClient) -import Convex.TradingBot.NodeClient.PricesClient (pricesClient) -import Convex.TradingBot.NodeClient.TradingClient (tradingClient) diff --git a/src/trading-bot/lib/Convex/TradingBot/NodeClient/BacktestingClient.hs b/src/trading-bot/lib/Convex/TradingBot/NodeClient/BacktestingClient.hs deleted file mode 100644 index 07e6f92f..00000000 --- a/src/trading-bot/lib/Convex/TradingBot/NodeClient/BacktestingClient.hs +++ /dev/null @@ -1,145 +0,0 @@ -{-# LANGUAGE LambdaCase #-} -{-# LANGUAGE NamedFieldPuns #-} -{-# LANGUAGE NumericUnderscores #-} -{-# LANGUAGE RankNTypes #-} -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE TypeApplications #-} -module Convex.TradingBot.NodeClient.BacktestingClient( - backtestingClient, - getOrderbookPrices -) where - -import Cardano.Api.Shelley (AssetName, Block (..), - BlockHeader (..), - BlockInMode (..), BlockNo, - CardanoMode, Env, Lovelace (..), - NetworkId, PolicyId, - Quantity (..), SlotNo, Value) -import qualified Cardano.Api.Shelley as C -import qualified Control.Concurrent.STM as STM -import Control.Lens (Lens', _2, anon, at, makeLenses, - use, view, (%=), (&), (.=), - (.~), (^.)) -import Control.Monad (guard, unless, void, when) -import Control.Monad.IO.Class (MonadIO (..)) -import Control.Monad.State.Strict (MonadState, execStateT) -import Control.Monad.Trans.Maybe (runMaybeT) -import qualified Convex.Constants as Constants -import Convex.Event (Event (..), NewOutputEvent (..), - OutputSpentEvent (..), - ResolvedInputs (..), - TxWithEvents (..), extract) -import qualified Convex.Lenses as L -import Convex.MonadLog (MonadLog, MonadLogKatipT (..), - logUnless) -import Convex.Muesli.LP.BuildTx (buyOrderFromScriptData) -import Convex.Muesli.LP.Types (BuyOrder (..), valueOf) -import Convex.NodeClient.Fold (CatchingUp (..), catchingUp, - foldClient) -import Convex.NodeClient.Resuming (resumingClient) -import Convex.NodeClient.Types (PipelinedLedgerStateClient) -import Convex.TradingBot.LPPoolEvent (LPPoolEvent (..), - OrderbookEvent (..)) -import qualified Convex.TradingBot.LPPoolEvent as LPPoolEvent -import Convex.TradingBot.Portfolio (Portfolio, - defaultPortfolioConfig, - emptyPortfolio) -import qualified Convex.TradingBot.Portfolio as Portfolio -import Convex.TradingBot.Prices (LPPrices) -import qualified Convex.TradingBot.Prices as Prices -import Convex.TradingBot.Rules (Rule, Signal (..)) -import Convex.TradingBot.Stats (LPStats) -import qualified Convex.TradingBot.Stats as Stats -import Data.Either (partitionEithers) -import Data.Foldable (toList, traverse_) -import Data.Map.Strict (Map) -import qualified Data.Map.Strict as Map -import Data.Maybe (fromMaybe, mapMaybe) -import qualified Katip as K -import Prelude hiding (log) - -data ClientState = - ClientState - { _resolvedInputs :: !(ResolvedInputs (Either LPPoolEvent OrderbookEvent)) - , _lpStats :: !LPStats - , _lastPrices :: !(Map (PolicyId, AssetName) (Lovelace, Quantity)) - , _lpPrices :: !(Map (PolicyId, AssetName) LPPrices) - , _portfolio :: !(Portfolio, Value) - } - -makeLenses ''ClientState - -initialState :: ClientState -initialState = ClientState mempty mempty mempty mempty (emptyPortfolio, C.lovelaceToValue $ Lovelace 3_000_000_000) - -backtestingClient :: Rule -> STM.TMVar (Portfolio, Value) -> K.LogEnv -> K.Namespace -> NetworkId -> Env -> PipelinedLedgerStateClient -backtestingClient rule resultVar logEnv ns networkId env = - resumingClient [Constants.lessRecent] $ \_ -> - foldClient - initialState - env - (applyBlock rule resultVar logEnv ns networkId) - -applyBlock :: Rule -> STM.TMVar (Portfolio, Value) -> K.LogEnv -> K.Namespace -> NetworkId -> CatchingUp -> ClientState -> BlockInMode CardanoMode -> IO (Maybe ClientState) -applyBlock rule resultVar le initialNamespace networkId c oldState block = K.runKatipContextT le () initialNamespace $ runMonadLogKatipT $ runMaybeT $ do - let (newEvents, newResolvedInputs) = extract LPPoolEvent.extract (oldState ^. resolvedInputs) block - BlockInMode (Block blockHeader _) _ = block - BlockHeader currentSlot _ currentBlockNo = blockHeader - newStats = - foldMap (foldMap Stats.fromEvent . toList . twEvents) newEvents - <> Stats.fromResolvedInputs newResolvedInputs - totalStats = (oldState ^. lpStats) <> newStats - newState = oldState - & resolvedInputs .~ newResolvedInputs - & lpStats .~ totalStats - flip execStateT newState $ do - updatePrices rule c currentBlockNo currentSlot - (Map.unionsWith (<>) (getOrderbookPrices networkId <$> newEvents)) - unless (catchingUp c) $ do - p <- use portfolio - liftIO (STM.atomically $ STM.putTMVar resultVar p) - guard False - -pricesFor :: (PolicyId, AssetName) -> Lens' ClientState LPPrices -pricesFor k = lpPrices . at k . anon Prices.empty Prices.null - -updatePrices :: (MonadLog m, MonadState ClientState m) => Rule -> CatchingUp -> BlockNo -> SlotNo -> Map (PolicyId, AssetName) (Lovelace, Quantity) -> m () -updatePrices rule c blck slt newPrices = do - oldPrices <- use lastPrices - flip traverse_ (Map.toList newPrices) $ \(k, newPrice) -> do - let oldPrice = Map.findWithDefault (0, 0) k oldPrices - pAt = Prices.pricesAt blck slt oldPrice newPrice - p = fromMaybe mempty $ Prices.price $ Prices._stats pAt - when (Prices.pmVolume p > 0) $ do - logUnless (catchingUp c) $ " " <> show (snd k) <> ": " <> Prices.showPriceMeasure p - pricesFor k %= Prices.prepend pAt - newPrices' <- use (pricesFor k) - portf <- use portfolio - portf' <- Portfolio.execSimulatedPortfolioT defaultPortfolioConfig portf $ do - let pricePoint = (fst k, snd k, snd newPrice, fst newPrice) - void (Portfolio.update pricePoint) - case rule newPrices' of - Buy -> void (Portfolio.buy 1.0 pricePoint) - Sell -> void (Portfolio.sell 1.0 pricePoint) - _ -> pure () - portfolio .= portf' - lastPrices .= oldPrices <> newPrices - -getOrderbookPrices :: NetworkId -> TxWithEvents (Either LPPoolEvent OrderbookEvent) -> Map (PolicyId, AssetName) (Lovelace, Quantity) -getOrderbookPrices networkId es = - case snd $ partitionEithers $ fmap sequence $ toList $ twEvents es of - [AnOutputSpentEvent a, AnOutputSpentEvent b] -> - let f OutputSpentEvent{oseDatum, oseTxOutput=NewOutputEvent{neOutput}} = - let vl = C.selectLovelace $ view (L._TxOut . _2 . L._TxOutValue) $ C.fromShelleyTxOut C.ShelleyBasedEraBabbage neOutput - dt = C.fromAlonzoData oseDatum - in case buyOrderFromScriptData networkId vl dt of - Just BuyOrder{buyCurrency, buyQuantity, buyPrice} -> - Just (buyCurrency, (valueOf buyQuantity buyPrice, buyQuantity)) - _ -> Nothing -- FIXME: sellOrderFromScriptData - in Map.fromListWith (<>) $ mapMaybe f [a, b] - _ -> mempty - --- TODO: --- backtesting for multiple sets of rules --- execution --- Add other LP dexes diff --git a/src/trading-bot/lib/Convex/TradingBot/NodeClient/OrderClient.hs b/src/trading-bot/lib/Convex/TradingBot/NodeClient/OrderClient.hs deleted file mode 100644 index e3dc6213..00000000 --- a/src/trading-bot/lib/Convex/TradingBot/NodeClient/OrderClient.hs +++ /dev/null @@ -1,98 +0,0 @@ -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE LambdaCase #-} -{-# LANGUAGE NamedFieldPuns #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE TypeApplications #-} -{-# LANGUAGE ViewPatterns #-} -{-| A wallet client for executing buy and sell orders --} -module Convex.TradingBot.NodeClient.OrderClient( - buyOrderClient, - sellOrderClient -) where - -import Cardano.Api (BlockInMode, CardanoMode, Env, - LocalNodeConnectInfo) -import qualified Cardano.Api as C -import Control.Applicative (Alternative (..)) -import Control.Lens (_3, preview, set, (&)) -import Control.Monad (void, when) -import Control.Monad.Trans.Maybe (runMaybeT) -import Convex.Class (runMonadBlockchainCardanoNodeT, - sendTx) -import Convex.CoinSelection (ERA, balanceForWallet) -import qualified Convex.Constants as Constants -import Convex.Lenses (emptyTx) -import qualified Convex.Lenses as L -import Convex.MonadLog (MonadLogKatipT (..), logInfoS) -import qualified Convex.Muesli.LP.BuildTx as BuildTx -import qualified Convex.Muesli.LP.Types as T -import Convex.NodeClient.Fold (CatchingUp (..), catchingUp, - foldClient) -import Convex.NodeClient.Resuming (resumingClient) -import Convex.NodeClient.Types (PipelinedLedgerStateClient) -import Convex.TradingBot.Cli.Config (Order (..)) -import Convex.Utxos (UtxoSet, apply, fromUtxoTx) -import qualified Convex.Utxos as Utxos -import Convex.Wallet (Wallet) -import qualified Convex.Wallet as Wallet -import Convex.Wallet.Cli.Config (ConfigMode (..)) -import Data.Proxy (Proxy (..)) -import qualified Katip as K - -buyOrderClient :: LocalNodeConnectInfo CardanoMode -> K.LogEnv -> K.Namespace -> Wallet -> Order 'Typed -> Env -> PipelinedLedgerStateClient -buyOrderClient info logEnv ns wallet order env = do - let network = C.localNodeNetworkId info - addr = Wallet.addressInEra network wallet & set (L._AddressInEra . L._Address . _3) namiStakeRef - tx = BuildTx.buyOrder addr Nothing (convBuyOrder order) emptyTx - resumingClient [Constants.recent] $ \_ -> - foldClient - mempty - env - (applyBlock info logEnv ns wallet tx) - -sellOrderClient :: LocalNodeConnectInfo CardanoMode -> K.LogEnv -> K.Namespace -> Wallet -> Order 'Typed -> Env -> PipelinedLedgerStateClient -sellOrderClient info logEnv ns wallet order env = do - let network = C.localNodeNetworkId info - addr = Wallet.addressInEra network wallet & set (L._AddressInEra . L._Address . _3) namiStakeRef - tx = BuildTx.sellOrder addr Nothing (convSellOrder order) emptyTx - resumingClient [Constants.recent] $ \_ -> - foldClient - mempty - env - (applyBlock info logEnv ns wallet tx) - -applyBlock :: LocalNodeConnectInfo CardanoMode -> K.LogEnv -> K.Namespace -> Wallet -> C.TxBodyContent C.BuildTx ERA -> CatchingUp -> UtxoSet C.CtxTx () -> BlockInMode CardanoMode -> IO (Maybe (UtxoSet C.CtxTx ())) -applyBlock info logEnv ns wallet tx (catchingUp -> isCatchingUp) state block = K.runKatipContextT logEnv () ns $ runMonadLogKatipT $ runMaybeT $ do - let change = Utxos.extract_ (Wallet.shelleyPaymentCredential wallet) state block - newState = apply state change - - when (not isCatchingUp) $ do - void $ runMonadBlockchainCardanoNodeT info $ do - (tx_, change_) <- balanceForWallet wallet (fromUtxoTx state) tx - logInfoS (show tx_) - logInfoS (show change_) - sendTx tx_ - empty - pure newState - -convBuyOrder :: Order 'Typed -> T.BuyOrder -convBuyOrder Order{policyId, assetName, quantity, lovelace} = - T.BuyOrder - { T.buyCurrency = (policyId, assetName) - , T.buyQuantity = quantity - , T.buyPrice = T.unitPrice quantity lovelace - } - -convSellOrder :: Order 'Typed -> T.SellOrder -convSellOrder Order{policyId, assetName, quantity, lovelace} = - T.SellOrder - { T.sellCurrency = (policyId, assetName) - , T.sellQuantity = quantity - , T.sellPrice = T.unitPrice quantity lovelace - } - -namiAddress :: C.AddressInEra C.BabbageEra -namiAddress = maybe (error "") id $ C.deserialiseAddress (C.proxyToAsType Proxy) "addr1qx4jckkq2gqey7pnzayptkfuxh93lrp79kqwl5zvuejgquurc9hqawk27ans9d45ss8pnukglu6mxpmnslvtznev6j0qd0dc2n" - -namiStakeRef = maybe (error "") id $ preview (L._AddressInEra . L._Address . _3) namiAddress diff --git a/src/trading-bot/lib/Convex/TradingBot/NodeClient/PricesClient.hs b/src/trading-bot/lib/Convex/TradingBot/NodeClient/PricesClient.hs deleted file mode 100644 index 0b02a879..00000000 --- a/src/trading-bot/lib/Convex/TradingBot/NodeClient/PricesClient.hs +++ /dev/null @@ -1,127 +0,0 @@ -{-# LANGUAGE LambdaCase #-} -{-# LANGUAGE NamedFieldPuns #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE TemplateHaskell #-} -{-| Extract prices from muesli trades to CSV --} -module Convex.TradingBot.NodeClient.PricesClient( - pricesClient, - PriceEventRow(..) -) where - -import qualified Cardano.Api as C -import Cardano.Api.Shelley (AssetName, BlockInMode, BlockNo, - CardanoMode, Env, Lovelace, - NetworkId, PolicyId, Quantity, - SlotNo, TxId) -import qualified Cardano.Api.Shelley as C -import Control.Lens (_2, makeLenses, view, (&), (.~), - (^.)) -import Control.Monad (guard) -import Control.Monad.IO.Class (MonadIO (..), liftIO) -import Control.Monad.Trans.Maybe (runMaybeT) -import qualified Convex.Constants as Constants -import Convex.Event (Event (..), NewOutputEvent (..), - OutputSpentEvent (..), - ResolvedInputs (..), - TxWithEvents (..), extract) -import qualified Convex.Lenses as L -import Convex.MonadLog (MonadLogKatipT (..)) -import Convex.Muesli.LP.BuildTx (buyOrderFromScriptData) -import Convex.Muesli.LP.Types (BuyOrder (..), valueOf) -import Convex.NodeClient.Fold (CatchingUp (..), catchingUp, - foldClient) -import Convex.NodeClient.Resuming (resumingClient) -import Convex.NodeClient.Types (PipelinedLedgerStateClient) -import Convex.TradingBot.LPPoolEvent (OrderbookEvent (..)) -import qualified Convex.TradingBot.LPPoolEvent as LPPoolEvent -import Data.Csv (FromField (..), (.:)) -import Data.CSV.Export (CSVRow (..), csvQuotationMark, - defaultCSVConfig, writeCSVLine) -import Data.Foldable (traverse_) -import Data.Proxy (Proxy (..)) -import qualified Data.Text as Text -import GHC.IO.Handle (Handle) -import qualified Katip as K -import Streaming.Cassava (FromNamedRecord (..)) - -data ClientState = - ClientState - { _resolvedInputs :: !(ResolvedInputs OrderbookEvent) - } - -makeLenses ''ClientState - -initialState :: ClientState -initialState = ClientState mempty - -pricesClient :: Handle -> NetworkId -> K.LogEnv -> K.Namespace -> Env -> PipelinedLedgerStateClient -pricesClient handle networkId logEnv ns env = - resumingClient [Constants.lessRecent] $ \_ -> - foldClient - initialState - env - (applyBlock handle networkId logEnv ns) - -applyBlock :: Handle -> NetworkId -> K.LogEnv -> K.Namespace -> CatchingUp -> ClientState -> BlockInMode CardanoMode -> IO (Maybe ClientState) -applyBlock handle networkId logEnv initialNamespace c oldState block = K.runKatipContextT logEnv () initialNamespace $ runMonadLogKatipT $ runMaybeT $ do - let (newEvents, newResolvedInputs) = extract (\e -> maybe Nothing (either (const Nothing) Just) . LPPoolEvent.extract e) (oldState ^. resolvedInputs) block - newState = oldState & resolvedInputs .~ newResolvedInputs - - flip traverse_ newEvents $ \TxWithEvents{twEvents, twTx, twBlock} -> do - let i = C.getTxId (C.getTxBody twTx) - config = defaultCSVConfig{csvQuotationMark=Nothing} - flip traverse_ twEvents $ \case - ANewOutputEvent{} -> pure () - AnOutputSpentEvent OutputSpentEvent{oseDatum, oseTxOutput = NewOutputEvent{neSlot, neOutput}} -> do - let vl = C.selectLovelace $ view (L._TxOut . _2 . L._TxOutValue) $ C.fromShelleyTxOut C.ShelleyBasedEraBabbage neOutput - dt = C.fromAlonzoData oseDatum - case buyOrderFromScriptData networkId vl dt of - Nothing -> pure () - Just BuyOrder{buyCurrency, buyQuantity, buyPrice} -> do - let row = PriceEventRow i neSlot twBlock (fst buyCurrency) (snd buyCurrency) buyQuantity (valueOf buyQuantity buyPrice) - liftIO (writeCSVLine handle config row) - - guard (catchingUp c) - pure newState - -data PriceEventRow = - PriceEventRow - { peTx :: TxId - , peSlot :: SlotNo - , peBlockNo :: BlockNo - , pePolicyId :: PolicyId - , peAssetName :: AssetName - , peQuantity :: Quantity - , peLovelace :: Lovelace - } - -instance CSVRow PriceEventRow where - headers _ = ["tx", "slot", "block", "policy", "asset", "quantity", "lovelace"] - toRow PriceEventRow{peTx, peSlot=C.SlotNo slot, peBlockNo=C.BlockNo n, pePolicyId, peAssetName, peQuantity=C.Quantity q, peLovelace=C.Lovelace l} = - [ C.serialiseToRawBytesHexText peTx - , Text.pack (show slot) - , Text.pack (show n) - , C.serialiseToRawBytesHexText pePolicyId - , C.serialiseToRawBytesHexText peAssetName - , Text.pack (show q) - , Text.pack (show l) - ] - -instance FromNamedRecord PriceEventRow where - parseNamedRecord m = - PriceEventRow - <$> fmap unFromHex (m .: "tx") - <*> fmap C.SlotNo (m .: "slot") - <*> fmap C.BlockNo (m .: "block") - <*> fmap unFromHex (m .: "policy") - <*> fmap unFromHex (m .: "asset") - <*> fmap C.Quantity (m .: "quantity") - <*> fmap C.Lovelace (m .: "lovelace") - -newtype FromHex a = FromHex{ unFromHex :: a } - -instance C.SerialiseAsRawBytes a => FromField (FromHex a) where - parseField bs = case C.deserialiseFromRawBytesHex (C.proxyToAsType Proxy) bs of - Right a -> pure (FromHex a) - Left err -> fail $ "parseField failed: " <> show err diff --git a/src/trading-bot/lib/Convex/TradingBot/NodeClient/TradingClient.hs b/src/trading-bot/lib/Convex/TradingBot/NodeClient/TradingClient.hs deleted file mode 100644 index 8e7ef62e..00000000 --- a/src/trading-bot/lib/Convex/TradingBot/NodeClient/TradingClient.hs +++ /dev/null @@ -1,137 +0,0 @@ -{-# LANGUAGE LambdaCase #-} -{-# LANGUAGE NamedFieldPuns #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE RankNTypes #-} -{-# LANGUAGE TemplateHaskell #-} -{-| Run the trading bot --} -module Convex.TradingBot.NodeClient.TradingClient( - tradingClient - ) where - -import Cardano.Api (AssetName, - Block (..), - BlockHeader (..), - BlockInMode (..), - BlockNo, - CardanoMode, - Env, Lovelace, - NetworkId, - PolicyId, - Quantity, - SlotNo, Value) -import qualified Cardano.Api as C -import Control.Lens (Lens', _2, - anon, at, - makeLenses, - set, use, (%=), - (&), (.=), - (^.)) -import Control.Monad (void, when) -import Control.Monad.State.Strict (MonadState, - execStateT) -import Control.Monad.Trans.Maybe (runMaybeT) -import qualified Convex.Constants as Constants -import Convex.Event (ResolvedInputs, - extract) -import Convex.MonadLog (MonadLog, - MonadLogKatipT (..), - logInfoS, - logUnless) -import Convex.NodeClient.Fold (CatchingUp (..), - catchingUp, - catchingUpWithNode, - foldClient) -import Convex.NodeClient.Resuming (resumingClient) -import Convex.NodeClient.Types (PipelinedLedgerStateClient) -import Convex.TradingBot.LPPoolEvent (OrderbookEvent (..)) -import qualified Convex.TradingBot.LPPoolEvent as LPPoolEvent -import Convex.TradingBot.NodeClient.BacktestingClient (getOrderbookPrices) -import Convex.TradingBot.Portfolio (Portfolio, - defaultPortfolioConfig, - emptyPortfolio) -import qualified Convex.TradingBot.Portfolio as Portfolio -import Convex.TradingBot.Prices (LPPrices) -import qualified Convex.TradingBot.Prices as Prices -import Convex.TradingBot.Rules (Rule, - Signal (..)) -import Convex.Utxos (UtxoSet) -import qualified Convex.Utxos as Utxos -import Convex.Wallet (Wallet) -import qualified Convex.Wallet as Wallet -import Data.Foldable (traverse_) -import Data.Map (Map) -import qualified Data.Map.Strict as Map -import Data.Maybe (fromMaybe) -import qualified Katip as K - -{-| State of the trading client --} -data ClientState = - ClientState - { _walletState :: !(UtxoSet C.CtxTx ()) - , _orderbookState :: !(ResolvedInputs OrderbookEvent) - , _lastPrices :: !(Map (PolicyId, AssetName) (Lovelace, Quantity)) - , _lpPrices :: !(Map (PolicyId, AssetName) LPPrices) - , _portfolio :: !(Portfolio, Value) - } - -makeLenses ''ClientState - -pricesFor :: (PolicyId, AssetName) -> Lens' ClientState LPPrices -pricesFor k = lpPrices . at k . anon Prices.empty Prices.null - - -initialState :: ClientState -initialState = ClientState mempty mempty mempty mempty (emptyPortfolio, mempty) - -tradingClient :: Rule -> K.LogEnv -> K.Namespace -> Wallet -> NetworkId -> Env -> PipelinedLedgerStateClient -tradingClient rule logEnv ns wallet networkId env = - let start = Constants.recent - in resumingClient [start] $ \_ -> - foldClient - (catchingUpWithNode start Nothing Nothing, initialState) - env - (applyBlock rule logEnv ns wallet networkId) - -applyBlock :: Rule -> K.LogEnv -> K.Namespace -> Wallet -> NetworkId -> CatchingUp -> (CatchingUp, ClientState) -> BlockInMode CardanoMode -> IO (Maybe (CatchingUp, ClientState)) -applyBlock rule logEnv ns wallet networkId c (oldC, state) block = K.runKatipContextT logEnv () ns $ runMonadLogKatipT $ runMaybeT $ do - let walletChange = Utxos.extract_ (Wallet.shelleyPaymentCredential wallet) (_walletState state) block - (orderBookEvents, newOrderBookState) = extract (\e -> maybe Nothing (either (const Nothing) Just) . LPPoolEvent.extract e) (state ^. orderbookState) block - newWalletState = Utxos.apply (state ^. walletState) walletChange - BlockInMode (Block blockHeader _) _ = block - BlockHeader currentSlot _ currentBlockNo = blockHeader - newState = state - & set walletState newWalletState - & set orderbookState newOrderBookState - & set (portfolio . _2) (Utxos.totalBalance newWalletState) - - state' <- flip execStateT newState $ do - updatePrices rule c currentBlockNo currentSlot (Map.unionsWith (<>) (getOrderbookPrices networkId . fmap Right <$> orderBookEvents)) - when (not (catchingUp c)) $ do - when (catchingUp oldC) (logInfoS "Caught up with node") - (pf, vl) <- use portfolio - logInfoS $ "AUM: " <> Portfolio.formatAda (Portfolio.aum vl pf) - pure (c, state') - -updatePrices :: (MonadLog m, MonadState ClientState m) => Rule -> CatchingUp -> BlockNo -> SlotNo -> Map (PolicyId, AssetName) (Lovelace, Quantity) -> m () -updatePrices rule c blck slt newPrices = do - oldPrices <- use lastPrices - flip traverse_ (Map.toList newPrices) $ \(k, newPrice) -> do - let oldPrice = Map.findWithDefault (0, 0) k oldPrices - pAt = Prices.pricesAt blck slt oldPrice newPrice - p = fromMaybe mempty $ Prices.price $ Prices._stats pAt - when (Prices.pmVolume p > 0) $ do - logUnless (catchingUp c) $ " " <> show (snd k) <> ": " <> Prices.showPriceMeasure p - pricesFor k %= Prices.prepend pAt - newPrices' <- use (pricesFor k) - portf <- use portfolio - portf' <- Portfolio.execSimulatedPortfolioT defaultPortfolioConfig portf $ Portfolio.runLoggingPortfolioT $ do - let pricePoint = (fst k, snd k, snd newPrice, fst newPrice) - void (Portfolio.update pricePoint) - case rule newPrices' of - Buy -> void (Portfolio.buy 1.0 pricePoint) - Sell -> void (Portfolio.sell 1.0 pricePoint) - _ -> pure () - portfolio .= portf' - lastPrices .= oldPrices <> newPrices diff --git a/src/trading-bot/lib/Convex/TradingBot/Portfolio.hs b/src/trading-bot/lib/Convex/TradingBot/Portfolio.hs deleted file mode 100644 index 715ee281..00000000 --- a/src/trading-bot/lib/Convex/TradingBot/Portfolio.hs +++ /dev/null @@ -1,376 +0,0 @@ -{-# LANGUAGE DerivingStrategies #-} -{-# LANGUAGE FlexibleInstances #-} -{-# LANGUAGE NamedFieldPuns #-} -{-# LANGUAGE NumericUnderscores #-} -{-# LANGUAGE RankNTypes #-} -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE TypeApplications #-} -{-# LANGUAGE UndecidableInstances #-} -module Convex.TradingBot.Portfolio( - -- * Positions - Position(..), - lastPrice, - stopLoss, - limit, - setLimits, - - -- * Portfolios - Portfolio(..), - printPortfolioInfo, - emptyPortfolio, - distribution, - tradeCount, - buyOrder, - updatePrice, - aum, - - -- * Config - PortfolioConfig(..), - defaultPortfolioConfig, - - -- * Executing trades - MonadTrade(..), - - -- ** Simulated portfolios - SimulatedPortfolioT, - runSimulatedPortfolioT, - execSimulatedPortfolioT, - - -- ** Real portfolios - - -- ** Logging - LoggingPortfolioT(..), - - -- * Etc. - availableFunds, - formatAda -) where - -import Cardano.Api (AssetId (..), AssetName, - Lovelace (..), PolicyId, - Quantity (..), Value) -import qualified Cardano.Api as C -import Control.Lens (Lens', _1, _2, _Just, at, - makeLenses, makeLensesFor, over, - set, use, view, (&), (+=), (.=), - (.~)) -import Control.Monad (guard, join, when) -import Control.Monad.IO.Class (MonadIO (..)) -import Control.Monad.Reader (ReaderT, ask, runReaderT) -import Control.Monad.State.Strict (MonadState, StateT, get, put, - runState, runStateT) -import Control.Monad.Trans.Class (MonadTrans (..)) -import Convex.MonadLog (MonadLog, logInfoS) -import Convex.Muesli.LP.Types (BuyOrder (..), Price, - SellOrder (..), scale, unitPrice, - unitsOf, valueOf) -import Data.Foldable (fold, traverse_) -import Data.Map.Strict (Map) -import qualified Data.Map.Strict as Map -import Data.Maybe (fromMaybe, isJust, isNothing) - -type PricePoint = (PolicyId, AssetName, Quantity, Lovelace) - -data PortfolioConfig = - PortfolioConfig - { pfMaxPositionSize :: !Rational -- ^ Max position size as a share of total AUM. Default: 0.10 - , pfDefaultStopLoss :: !Rational -- ^ Default stop loss on positions (as a fraction of the initial price. Default: 0.75) - , pfDefaultLimit :: !Rational -- ^ Default limit (Take profit) on positions as a multipe of the initial price. Default: 1.25 - , pfMinPositionSize :: !Lovelace -- ^ Minimum position size in Ada - , pfFee :: !Lovelace -- ^ Fee for each trade (txn fee, matchmaker fee, etc.) - } - deriving Show - -defaultPortfolioConfig :: PortfolioConfig -defaultPortfolioConfig = - PortfolioConfig - { pfMaxPositionSize = 0.1 - , pfDefaultStopLoss = 0.85 - , pfDefaultLimit = 1.35 - , pfMinPositionSize = Lovelace 10_000_000 - , pfFee = Lovelace 2_500_000 - } - -{-| Position in our portfolio. Note that this does not include the -size of the position (this information is obtained from the wallet -in form of a 'Value' value) --} -data Position = - Position - { pLastPrice :: !Price -- ^ last market price per unit of currency - , pStopLoss :: Maybe Price -- ^ stop (price per unit of currency) - , pLimit :: Maybe Price - } - deriving (Eq, Ord, Show) - -makeLensesFor - [ ("pLastPrice", "lastPrice") - , ("pStopLoss", "stopLoss") - , ("pLimit", "limit") - ] - ''Position - -initPosition :: Price -> Position -initPosition p = Position p Nothing Nothing - -setLimits :: PortfolioConfig -> Position -> Position -setLimits PortfolioConfig{pfDefaultLimit, pfDefaultStopLoss} position@Position{pLastPrice} = - position - & set stopLoss (Just $ pfDefaultStopLoss `scale` pLastPrice) - & set limit (Just $ pfDefaultLimit `scale` pLastPrice) - --- | Whether the stop loss of the position has been triggered -triggerStopLoss :: Position -> Bool -triggerStopLoss Position{pStopLoss, pLastPrice} = - maybe False (\sl -> sl > pLastPrice) pStopLoss - --- | Whether the limit of the position has been triggered -triggerLimit :: Position -> Bool -triggerLimit Position{pLimit, pLastPrice} = - maybe False (\l -> l < pLastPrice) pLimit - -{-| Simulated portfolio for testing --} -data Portfolio = Portfolio - { _positions :: !(Map (PolicyId, AssetName) Position) - , _tradeCount :: !Int - } - -makeLenses ''Portfolio - --- | Create a buy order if it conforms with the portfolio configuration -buyOrder :: PortfolioConfig -> Value -> Portfolio -> PolicyId -> AssetName -> Maybe BuyOrder -buyOrder PortfolioConfig{pfMaxPositionSize, pfMinPositionSize} vl portfolio p a = do - let Lovelace totalAum = aum vl portfolio - Lovelace currentAllocation = allocatedTo vl portfolio p a - maxAllocation = pfMaxPositionSize * fromIntegral totalAum - newPositionSize = Lovelace (floor (maxAllocation - fromIntegral currentAllocation)) - guard (newPositionSize > 0) - guard (newPositionSize > pfMinPositionSize) - Position{pLastPrice} <- view (position p a) portfolio - guard (pLastPrice > 0) - let units = unitsOf newPositionSize pLastPrice - pure - BuyOrder - { buyCurrency = (p, a) - , buyQuantity = units - , buyPrice = pLastPrice - } - --- TODO: don't need PricePoint in sellOrder - -sellOrder :: Value -> PricePoint -> SellOrder -sellOrder vl (p, a, q, l) = - let currentSize = C.selectAsset vl (AssetId p a) - price = unitPrice q l - in SellOrder{sellCurrency = (p, a), sellQuantity = currentSize, sellPrice = price } - --- | Update the portfolio with the price point -updatePrice :: PortfolioConfig -> Value -> Portfolio -> PricePoint -> (Maybe SellOrder, Portfolio) -updatePrice config vl portfolio (p, a, q, l) = flip runState portfolio $ do - let currentSize = C.selectAsset vl (AssetId p a) - price = unitPrice q l - pos <- use (position p a) - case pos of - -- first time we are seeing this currency, make a new position. - Nothing -> do - let pos' = initPosition price - pos'' = if currentSize > 0 then (setLimits config pos') else pos' - position p a .= Just pos'' - pure Nothing - -- update the position - Just pos_ - | currentSize > 0 && isJust (pStopLoss pos_) -> do - let pos' = updatePosition q l pos_ - position p a .= Just pos' - if (triggerStopLoss pos' || triggerLimit pos') - then pure $ Just $ SellOrder{sellCurrency = (p, a), sellQuantity = currentSize, sellPrice = price } - else pure Nothing - | currentSize > 0 || isNothing (pStopLoss pos_) -> do - let pos' = updatePosition q l (setLimits config pos_) - position p a .= Just pos' - pure Nothing - | otherwise -> do - let pos' = initPosition price - position p a .= Just pos' - pure Nothing - -{-| Initialise the portfolio with the amount of Ada available for purchases --} -emptyPortfolio :: Portfolio -emptyPortfolio = Portfolio{_positions = mempty, _tradeCount = 0} - -{-| Distribution of non-Ada assets, priced in Ada --} -distribution :: - Value -- ^ Sum of all assets in the portfolio - -> Portfolio -- ^ List of positions and prices - -> Map AssetId Lovelace -distribution value Portfolio{_positions} = - let getPrice assetId = maybe 0 pLastPrice (Map.lookup assetId _positions) - k (AssetId p a, quantity) = (AssetId p a, valueOf quantity (getPrice (p, a))) - k (AdaAssetId, Quantity quantity) = (AdaAssetId, Lovelace quantity) - in Map.fromList - $ fmap k (C.valueToList value) - --- | Total "assets under management" -aum :: Value -> Portfolio -> Lovelace -aum vl pf = fold (distribution vl pf) - -{-| Lovelace amount allocated to the native asset --} -allocatedTo :: Value -> Portfolio -> PolicyId -> AssetName -> Lovelace -allocatedTo vl Portfolio{_positions} p a = fromMaybe 0 $ do - Position{pLastPrice} <- Map.lookup (p, a) _positions - let q = C.selectAsset vl (AssetId p a) - pure (valueOf q pLastPrice) - -updatePosition :: Quantity -> Lovelace -> Position -> Position -updatePosition q l p = - let oldPrice = view lastPrice p - newPrice = unitPrice q l - diff = max 0 (newPrice - oldPrice) - in p - & lastPrice .~ newPrice - -- update the stop loss (trailing stop loss) - & over (stopLoss . _Just) (+ diff) - -position :: PolicyId -> AssetName -> Lens' Portfolio (Maybe Position) -position p a = positions . at (p, a) - -formatAda :: Lovelace -> String -formatAda (Lovelace v) = show (round @Double @Integer (fromIntegral v / (1_000_000 :: Double))) - -printPortfolioInfo :: (MonadLog m) => Value -> Portfolio -> m () -printPortfolioInfo vl p@Portfolio{_positions, _tradeCount}= do - let lvl = aum vl p - numPos = pred (length $ C.valueToList vl) - logInfoS $ "Portfolio value: " <> formatAda lvl <> " with " <> show numPos <> " native assets and " <> formatAda (C.selectLovelace vl) <> " Ada in cash. Made " <> show _tradeCount <> " trades." - -{-| How much Ada we can spend on a particular asset, considering -* the amount already invested in this asset -* the available cash -* the configuration in 'PortfolioConfig' --} -availableFunds :: PortfolioConfig -> Value -> Portfolio -> PolicyId -> AssetName -> Lovelace -availableFunds PortfolioConfig{pfMaxPositionSize, pfFee} vl portfolio p a = - let Lovelace totalLvl = aum vl portfolio - Lovelace alloc = allocatedTo vl portfolio p a - Lovelace cash = C.selectLovelace vl - pfFee - maxAvailable = pfMaxPositionSize * fromIntegral totalLvl - remaining = min (max 0 cash) (floor (max 0 (maxAvailable - fromIntegral alloc))) - in Lovelace remaining - -type Confidence = Double - -class Monad m => MonadTrade m where - update :: PricePoint -> m (Maybe SellOrder) -- ^ Update the positions with new pricing data - buy :: Confidence -> PricePoint -> m (Maybe BuyOrder) - sell :: Confidence -> PricePoint -> m (Maybe SellOrder) - -newtype SimulatedPortfolioT m a = SimulatedPortfolioT{ unSimulatedPortfolioT :: ReaderT PortfolioConfig (StateT (Portfolio, Value) m) a } - deriving newtype (Functor, Applicative, Monad, MonadIO, MonadLog) - -instance MonadTrans SimulatedPortfolioT where - lift = SimulatedPortfolioT . lift . lift - -instance MonadState s m => MonadState s (SimulatedPortfolioT m) where - get = lift get - put s = lift (put s) - -runSimulatedPortfolioT :: PortfolioConfig -> (Portfolio, Value) -> SimulatedPortfolioT m a -> m (a, (Portfolio, Value)) -runSimulatedPortfolioT config portfolio SimulatedPortfolioT{unSimulatedPortfolioT} = - runStateT (runReaderT unSimulatedPortfolioT config ) portfolio - -execSimulatedPortfolioT :: Functor m => PortfolioConfig -> (Portfolio, Value) -> SimulatedPortfolioT m a -> m (Portfolio, Value) -execSimulatedPortfolioT config portfolio = fmap snd <$> runSimulatedPortfolioT config portfolio - -instance (Monad m) => MonadTrade (SimulatedPortfolioT m) where - update pricePoint = SimulatedPortfolioT $ do - (p, v) <- get - c <- ask - let (sellOrder', p') = updatePrice c v p pricePoint - put (p', v) - join <$> traverse (applySellOrder c) sellOrder' - - sell _confidence pricePoint = SimulatedPortfolioT $ do - (_, v) <- get - c <- ask - applySellOrder c (sellOrder v pricePoint) - - buy _confidence (p, a, _, _) = SimulatedPortfolioT $ do - (portfolio, v) <- get - c <- ask - let order = buyOrder c v portfolio p a - join <$> traverse (applyBuyOrder c) order - -applySellOrder :: (MonadState (Portfolio, Value) m) => PortfolioConfig -> SellOrder -> m (Maybe SellOrder) -applySellOrder PortfolioConfig{pfFee} o@SellOrder{sellCurrency, sellQuantity, sellPrice} = do - oldV <- use _2 - let lvl = valueOf sellQuantity sellPrice - newV = oldV - <> C.lovelaceToValue lvl - <> C.negateValue (C.valueFromList [(uncurry C.AssetId sellCurrency, sellQuantity)]) - <> C.negateValue (C.lovelaceToValue pfFee) - allPos = all (\q -> q > 0) $ fmap snd $ C.valueToList newV - if allPos && lvl > pfFee - then do - _2 .= newV - _1 . tradeCount += 1 - pure (Just o) - else pure Nothing - -applyBuyOrder :: (MonadState (Portfolio, Value) m) => PortfolioConfig -> BuyOrder -> m (Maybe BuyOrder) -applyBuyOrder PortfolioConfig{pfFee} o@BuyOrder{buyCurrency, buyQuantity, buyPrice} = do - oldV <- use _2 - let lvl = valueOf buyQuantity buyPrice - newV = oldV - <> C.negateValue (C.lovelaceToValue lvl) - <> (C.valueFromList [(uncurry C.AssetId buyCurrency, buyQuantity)]) - <> C.negateValue (C.lovelaceToValue pfFee) - allPos = all (\q -> q > 0) $ fmap snd $ C.valueToList newV - if allPos && lvl > pfFee - then do - _2 .= newV - _1 . tradeCount += 1 - pure (Just o) - else pure Nothing - -newtype LoggingPortfolioT m a = LoggingPortfolioT{ runLoggingPortfolioT :: m a } - deriving newtype (Functor, Applicative, Monad, MonadIO, MonadLog) - -instance MonadTrans LoggingPortfolioT where - lift = LoggingPortfolioT - -instance MonadState s m => MonadState s (LoggingPortfolioT m) where - get = lift get - put s = lift (put s) - -instance (MonadLog m, MonadTrade m) => MonadTrade (LoggingPortfolioT m) where - update pricePoint = LoggingPortfolioT $ do - so <- update pricePoint - traverse_ logSellOrder so - pure so - sell confidence pricePoint = LoggingPortfolioT $ do - so <- sell confidence pricePoint - traverse_ logSellOrder so - pure so - buy confidence pricePoint = LoggingPortfolioT $ do - bo <- buy confidence pricePoint - traverse_ logBuyOrder bo - pure bo - -logSellOrder :: MonadLog m => SellOrder -> m () -logSellOrder SellOrder{sellCurrency, sellQuantity, sellPrice} = - logOrder "SELL" (snd sellCurrency) sellQuantity sellPrice - -logBuyOrder :: MonadLog m => BuyOrder -> m () -logBuyOrder BuyOrder{buyCurrency, buyQuantity, buyPrice} = - logOrder "BUY " (snd buyCurrency) buyQuantity buyPrice - -logOrder :: MonadLog m => String -> AssetName -> Quantity -> Price -> m () -logOrder nm assetName quantity price = do - let ada = valueOf quantity price - Quantity q = quantity - when (ada >= 1_000_000) $ - logInfoS $ nm <> " " <> show q <> " " <> show assetName <> " for " <> formatAda ada <> " Ada" diff --git a/src/trading-bot/lib/Convex/TradingBot/Prices.hs b/src/trading-bot/lib/Convex/TradingBot/Prices.hs deleted file mode 100644 index 4e39ebe9..00000000 --- a/src/trading-bot/lib/Convex/TradingBot/Prices.hs +++ /dev/null @@ -1,163 +0,0 @@ -{-# LANGUAGE NamedFieldPuns #-} -{-| Keeping track of asset prices --} -module Convex.TradingBot.Prices( - PriceMeasure(..), - observeLP, - showPriceMeasure, - AssetPrices(..), - price, - - -- * Statistics over time - LPPrices, - prepend, - PricesAt(..), - pricesAt, - empty, - null, - splitLastNSlots, - lastHour, - lastDay, - lastWeek, - stats, - toList -) where - -import Cardano.Api (BlockNo, Lovelace (..), Quantity (..), - SlotNo) -import Convex.Measures (Mean, countMany, getMean) -import Data.FingerTree (FingerTree, Measured (..), split, (<|)) -import qualified Data.FingerTree as FT -import qualified Data.Foldable as F -import Data.Maybe.Strict (StrictMaybe (SJust, SNothing)) -import Prelude hiding (null) - -data PriceMeasure = - PriceMeasure - { pmPrice :: !Mean -- ^ Price per unit in Lovelace - , pmVolume :: !Lovelace -- ^ Traded volume in Lovelace - } - -instance Semigroup PriceMeasure where - l <> r = - PriceMeasure - { pmPrice = pmPrice l <> pmPrice r - , pmVolume = pmVolume l + pmVolume r - } - -instance Monoid PriceMeasure where - mempty = PriceMeasure mempty mempty - -showPriceMeasure :: PriceMeasure -> String -showPriceMeasure PriceMeasure{pmPrice, pmVolume} = - let m = maybe "N/A" show (getMean pmPrice) - in unwords ["Price:", m, "Volume:", show pmVolume] - -{-| Measure the price and volume, given the old and the new contents of the LP --} -observeLP :: - (Lovelace, Quantity) -> - (Lovelace, Quantity) -> - PriceMeasure -observeLP (Lovelace oldLvl, _) (Lovelace newLvl, Quantity newQ) = - let lvlDiff = abs (oldLvl - newLvl) - in PriceMeasure - { pmPrice = countMany (fromIntegral newQ) newLvl - , pmVolume = Lovelace lvlDiff - } - -data AssetPrices = - AssetPrices - { apPrice :: !(StrictMaybe PriceMeasure) - , apSlotRange :: !(StrictMaybe (SlotNo, SlotNo)) - } - -price :: AssetPrices -> Maybe PriceMeasure -price AssetPrices{apPrice} = case apPrice of - SJust a -> Just a - SNothing -> Nothing - -smMappend :: Semigroup a => StrictMaybe a -> StrictMaybe a -> StrictMaybe a -smMappend x y = case (x, y) of - (SNothing, k) -> k - (k, SNothing) -> k - (SJust l, SJust k) -> SJust (l <> k) - -instance Semigroup AssetPrices where - l <> r = - AssetPrices - { apPrice = smMappend (apPrice l) (apPrice r) - , apSlotRange = - case (apSlotRange l, apSlotRange r) of - (SNothing, x) -> x - (x, SNothing) -> x - (SJust (fromL, toL), SJust (fromR, toR)) -> SJust (min fromL fromR, max toL toR) - } - -instance Monoid AssetPrices where - mempty = AssetPrices SNothing SNothing - -{-| Asset prices observed at a point in time --} -data PricesAt = - PricesAt - { _blockNo :: BlockNo - , _slotNo :: SlotNo - , _stats :: AssetPrices - } - -instance Measured AssetPrices PricesAt where - measure = _stats - -pricesAt :: BlockNo -> SlotNo -> (Lovelace, Quantity) -> (Lovelace, Quantity) -> PricesAt -pricesAt _blockNo _slotNo old new = - PricesAt - { _blockNo - , _slotNo - , _stats = AssetPrices{apPrice = SJust (observeLP old new), apSlotRange = SJust (_slotNo, _slotNo)} - } - -newtype LPPrices = LPPrices{unLPPrices :: FingerTree AssetPrices PricesAt } - -prepend :: PricesAt -> LPPrices -> LPPrices -prepend s LPPrices{unLPPrices} = LPPrices $ s <| unLPPrices - -empty :: LPPrices -empty = LPPrices mempty - -null :: LPPrices -> Bool -null LPPrices{unLPPrices} = FT.null unLPPrices - -splitLastNSlots :: Int -> LPPrices -> (LPPrices, LPPrices) -splitLastNSlots n (LPPrices s) = - case (apSlotRange $ measure s) of - SNothing -> (LPPrices mempty, LPPrices s) - SJust (_, maxSlot) -> - let cutoffPoint :: SlotNo = maxSlot - (fromIntegral n) - f AssetPrices{apSlotRange = SNothing} = True - f AssetPrices{apSlotRange = SJust (minSlot', _)} = minSlot' < cutoffPoint - (this, that) = split f s - in (LPPrices this, LPPrices that) - --- | Split a 'MuesliStats' value into one with the values for the last hour --- and one with the rest -lastHour :: LPPrices -> (LPPrices, LPPrices) -lastHour = splitLastNSlots (60 * 60) - --- | Split a 'LPPrices' value into one with the values for the last day --- and one with the rest -lastDay :: LPPrices -> (LPPrices, LPPrices) -lastDay = splitLastNSlots (60 * 60 * 24) - --- | Split a 'LPPrices' value into one with the values for the last week --- and one with the rest -lastWeek :: LPPrices -> (LPPrices, LPPrices) -lastWeek = splitLastNSlots (60 * 60 * 24 * 7) - --- | The raw stats -stats :: LPPrices -> AssetPrices -stats = measure . unLPPrices - --- | A list with all stats that were recorded -toList :: LPPrices -> [PricesAt] -toList = F.toList . unLPPrices diff --git a/src/trading-bot/lib/Convex/TradingBot/Rules.hs b/src/trading-bot/lib/Convex/TradingBot/Rules.hs deleted file mode 100644 index d965e76f..00000000 --- a/src/trading-bot/lib/Convex/TradingBot/Rules.hs +++ /dev/null @@ -1,116 +0,0 @@ -{-# LANGUAGE DeriveAnyClass #-} -{-# LANGUAGE DerivingStrategies #-} -{-# LANGUAGE NamedFieldPuns #-} -{-# LANGUAGE NumericUnderscores #-} -module Convex.TradingBot.Rules( - Signal(..), - Rule, - SearchableRule(..), - - -- * Concrete rules - - -- ** Two moving averages - TwoMovingAverages(..), - twoMovingAverages, - - -- * One moving average over two adjacent time periods - MovingAverages(..), - movingAverages -) where - -import Control.DeepSeq (NFData) -import Control.Monad (guard) -import Control.Monad.Primitive (PrimMonad, PrimState) -import Convex.Measures (getMean) -import Convex.TradingBot.Prices (LPPrices, splitLastNSlots, - stats) -import qualified Convex.TradingBot.Prices as Prices -import Data.Maybe (fromMaybe) -import GHC.Generics (Generic) -import qualified System.Random.MWC.Probability as P -import System.Random.MWC.Probability (Gen) - -type Rule = LPPrices -> Signal - -{-| Rules whose parameter space can be searched by a random walk --} -class SearchableRule r where - {-| Apply the rule to a set of historic prices to obtain a signal - -} - signal :: r -> Rule - neighbours :: PrimMonad m => Gen (PrimState m) -> r -> m r - -data Signal = Buy | Sell | Hold - deriving (Eq, Ord, Show) - -twoMovingAverages :: TwoMovingAverages -twoMovingAverages = TwoMovingAverages 1.15 0.8 (60 * 60 * 24 * 7) (60 * 60 * 24) - -instance SearchableRule TwoMovingAverages where - signal TwoMovingAverages{rdBuy, rdSell, rdLookbackBig, rdLookbackSmall} prices = fromMaybe Hold $ do - pmWeek <- Prices.price (stats $ fst $ splitLastNSlots rdLookbackBig prices) >>= getMean . Prices.pmPrice - pmDay <- Prices.price (stats $ fst $ splitLastNSlots rdLookbackSmall prices) >>= getMean . Prices.pmPrice - if (pmWeek > pmDay * rdBuy) - then pure Buy - else if pmWeek < pmDay * rdSell - then pure Sell - else pure Hold - - neighbours gen TwoMovingAverages{rdBuy, rdSell, rdLookbackBig, rdLookbackSmall} = do - let sv = 0.01 - buy' <- max 0.1 <$> P.sample (P.normal rdBuy sv) gen - sell' <- max 0.1 <$> P.sample (P.normal rdSell sv) gen - pure - $ TwoMovingAverages - { rdBuy = max buy' sell' - , rdSell = min buy' sell' - , rdLookbackBig - , rdLookbackSmall - } - -data TwoMovingAverages = - TwoMovingAverages - { rdBuy :: !Double -- ^ Threshold for buy signal - , rdSell :: !Double -- ^ Threshold for sell signal - , rdLookbackBig :: !Int -- ^ Size of the "large" lookback window in seconds - , rdLookbackSmall :: !Int -- ^ Size of the "small" lookback window in seconds - } - deriving stock (Eq, Generic, Show) - deriving anyclass NFData - -data MovingAverages = - MovingAverages - { maPeriod :: !Int -- ^ Size of the lookback window in seconds - , maBuyThreshold :: !Double - , maSellThreshold :: !Double - } - deriving stock (Eq, Generic, Show) - deriving anyclass NFData - -instance SearchableRule MovingAverages where - signal MovingAverages{maPeriod, maBuyThreshold, maSellThreshold} prices = fromMaybe Hold $ do - let getValue x = Prices.price (stats $ fst $ splitLastNSlots maPeriod x) >>= getMean . Prices.pmPrice - current <- getValue prices - previous <- getValue (snd $ splitLastNSlots 1 prices) - guard (previous /= 0) - let r = current / previous - if r > 1 + maBuyThreshold - then pure Buy - else - if r < 1 - maSellThreshold - then pure Sell - else pure Hold - - neighbours gen MovingAverages{maPeriod, maBuyThreshold, maSellThreshold} = do - period' <- max (60 * 60) . round <$> P.sample (P.normal (fromIntegral maPeriod) 10_000) gen - threshold' <- abs <$> P.sample (P.normal maBuyThreshold 0.1) gen - threshold'' <- abs <$> P.sample (P.normal maSellThreshold 0.1) gen - pure - $ MovingAverages - { maPeriod = period' - , maBuyThreshold = threshold' - , maSellThreshold = threshold'' - } - -movingAverages :: MovingAverages -movingAverages = MovingAverages (60 * 60 * 24 * 7) 0.01 0.01 diff --git a/src/trading-bot/lib/Convex/TradingBot/Stats.hs b/src/trading-bot/lib/Convex/TradingBot/Stats.hs deleted file mode 100644 index e431cb4e..00000000 --- a/src/trading-bot/lib/Convex/TradingBot/Stats.hs +++ /dev/null @@ -1,124 +0,0 @@ -{-# LANGUAGE LambdaCase #-} -{-# LANGUAGE NamedFieldPuns #-} -{-# LANGUAGE TemplateHaskell #-} -module Convex.TradingBot.Stats( - LPStats(..), - outputsCreated, - outputsSpent, - outputCount, - fromEvent, - fromResolvedInputs, - - -- * Output counts - OutputCount(..), - numLPPools, - numOrderBookOutputs, - - -- * Script counts - ScriptCount(..), - prettyStats, - fromScriptType, - poolEvents -) where - -import Control.Lens (makeLenses, over, (&), (.~)) -import Convex.Event (Event (..), NewOutputEvent (..), - OutputSpentEvent (..), - ResolvedInputs (..)) -import Convex.TradingBot.LPPoolEvent (LPPoolEvent (..), - OrderbookEvent) -import Data.Either (isRight) -import Data.List (intercalate) -import qualified Data.Map as Map - -data ScriptCount = - ScriptCount - { _poolEvents :: !Int - , _orderBookEvents :: !Int - } - -makeLenses ''ScriptCount - -instance Semigroup ScriptCount where - l <> r = - ScriptCount - { _poolEvents = _poolEvents l + _poolEvents r - , _orderBookEvents = _orderBookEvents l + _orderBookEvents r - } - -instance Monoid ScriptCount where - mempty = ScriptCount 0 9 - -data OutputCount = - OutputCount - { _numLPPools :: !Int - , _numOrderBookOutputs :: !Int - } - -makeLenses ''OutputCount - -instance Semigroup OutputCount where - _ <> r = r - -data LPStats = - LPStats - { _outputsCreated :: !ScriptCount - , _outputsSpent :: !ScriptCount - , _outputCount :: !(Maybe OutputCount) - } - -makeLenses ''LPStats - -instance Semigroup LPStats where - l <> r = - LPStats - { _outputsCreated = _outputsCreated l <> _outputsCreated r - , _outputsSpent = _outputsSpent l <> _outputsSpent r - , _outputCount = _outputCount l <> _outputCount r - } - -instance Monoid LPStats where - mempty = LPStats mempty mempty mempty - -fromScriptType :: (Either LPPoolEvent OrderbookEvent) -> ScriptCount -fromScriptType st = - let l = case st of - Left LPPoolEvent{} -> poolEvents - Right _ -> orderBookEvents - in mempty & over l succ - -fromEvent :: Event (Either LPPoolEvent OrderbookEvent) -> LPStats -fromEvent = \case - AnOutputSpentEvent OutputSpentEvent{oseTxOutput=NewOutputEvent{neEvent}} -> - mempty & outputsSpent .~ fromScriptType neEvent - ANewOutputEvent NewOutputEvent{neEvent} -> - mempty & outputsCreated .~ fromScriptType neEvent - -fromResolvedInputs :: ResolvedInputs (Either LPPoolEvent OrderbookEvent) -> LPStats -fromResolvedInputs (ResolvedInputs mp) = - let (lp, orderBook) = Map.partition (isRight . neEvent) mp - in mempty - & outputCount .~ Just (OutputCount (Map.size lp) (Map.size orderBook)) - -prettyCount :: ScriptCount -> String -prettyCount ScriptCount{_poolEvents} = - intercalate ", " - $ fmap (\(n, s) -> unwords [n <> ":", show s]) - $ filter (\(_, s) -> s > 0) - $ [ ("Pool script", _poolEvents) - ] - -prettyStats :: LPStats -> String -prettyStats LPStats{_outputsCreated, _outputsSpent, _outputCount} = - let x1 = prettyCount _outputsCreated - x2 = prettyCount _outputsCreated - x3 = case _outputCount of - Just (OutputCount i j) | i+j > 0 -> "LPs: " <> show i <> ", orders: " <> show j - _ -> "" - in intercalate ", " - $ fmap (\(n, s) -> unwords [n, s]) - $ filter (not . null . snd) - $ [ ("Outputs created:", x1) - , ("Outputs spent:", x2) - , ("Active outputs:", x3) - ]