Esempio n. 1
0
def Canceller(ctx):

    ctx.volumeStep = 15

    return [
        ctx.makeTrader_A(strategy.LiquidityProviderSide(side = Side.Sell),
                         "LiquidityProvider-"),
        
        ctx.makeTrader_A(strategy.LiquidityProviderEx(
                            orderFactory=order.WithExpiryFactory(
                                    expirationDistr=mathutils.constant(1))),
                         "LiquidityProviderEx-"),
        
        ctx.makeTrader_A(strategy.LiquidityProviderSide(side = Side.Buy),
                         "LiquidityProviderBuy"),
    
        ctx.makeTrader_A(   strategy.Array([
                                strategy.LiquidityProviderSide(side = Side.Sell),
                                strategy.Canceller()
                            ]),
                           label = "LiquidityProviderWithCanceller"),
        
        ctx.makeTrader_A(  strategy.LiquidityProviderSide(
                                side = Side.Sell,
                                orderFactoryT=order.WithExpiryFactory(
                                    expirationDistr=mathutils.constant(10))),
                           "LiquidityProviderWithExpiry"),
        
        ctx.makeTrader_A(   strategy.FundamentalValue(
                                fundamentalValue = mathutils.constant(1000)), 
                            "fv_1000")
        ]
def TradeIfProfitable(ctx):

    ctx.volumeStep = 30
    
    alpha_slow = 0.015
    alpha_fast = 0.15

    slow = lambda: mathutils.ewma(alpha = alpha_slow)
    fast = lambda: mathutils.ewma(alpha = alpha_fast)

    linear_signal = signal.RandomWalk(initialValue=200, 
                                      deltaDistr=const(-1), 
                                      label="200-t")
    
    demo = ctx.addGraph('demo')
    myVolume = lambda: [(observable.VolumeTraded(), demo)]
    myAverage = lambda alpha: [(observable.avg(observable.Price(orderbook.OfTrader()), alpha), demo)]
    
    avg_plus = strategy.TwoAverages(average1 = slow(), 
                                    average2 = fast(),
                                    creationIntervalDistr = mathutils.constant(1.),
                                    volumeDistr           = mathutils.constant(1.))
    
    avg_minus = strategy.TwoAverages(average1 = fast(), 
                                     average2 = slow(),
                                     creationIntervalDistr = mathutils.constant(1.),
                                     volumeDistr           = mathutils.constant(1.))
    
    avg_plus_opt = strategy.TradeIfProfitable(avg_plus)
    avg_minus_opt = strategy.TradeIfProfitable(avg_minus)

    return [
        ctx.makeTrader_A(strategy.LiquidityProvider(volumeDistr=const(45)),
                         "liquidity"),

        ctx.makeTrader_A(strategy.Signal(linear_signal,
                                         volumeDistr=const(20)), 
                        "signal", 
                        [(linear_signal, ctx.amount_graph)]),
            
        ctx.makeTrader_A(avg_plus, 
                        'avg+', 
                        myAverage(alpha_slow) + myAverage(alpha_fast) + myVolume()),

        ctx.makeTrader_A(avg_minus, 
                         'avg-',
                         myVolume()),

        ctx.makeTrader_A(avg_plus_opt, 
                         'avg+ opt',
                         myVolume()),

        ctx.makeTrader_A(avg_minus_opt, 
                         'avg- opt',
                         myVolume()),
    ]
Esempio n. 3
0
def FundamentalValue(ctx):
    
    ctx.volumeStep = 30
    fv = 200

    demo = ctx.addGraph('demo')
    myVolume = lambda: [(observable.VolumeTraded(), demo)]
    myPrice = lambda: [(observable.Price(orderbook.OfTrader()), demo)]

    return [
        ctx.makeTrader_A( 
            strategy.LiquidityProvider(
                 volumeDistr=mathutils.constant(6),
                 orderFactoryT=order.WithExpiryFactory(
                     expirationDistr=mathutils.constant(10))),
            "liquidity"),
    
        ctx.makeTrader_A( 
            strategy.FundamentalValue(
               fundamentalValue = mathutils.constant(fv),
               creationIntervalDistr = mathutils.constant(1.),
               volumeDistr = mathutils.constant(1)), 
            "fv_200", 
            myVolume() + myPrice() + Constant(fv, demo)),

        ctx.makeTrader_A(
            strategy.FundamentalValueEx(
               fundamentalValue = mathutils.constant(fv),
               creationIntervalDistr = mathutils.constant(1.),
               volumeDistr = mathutils.constant(1)), 
            "fv_ex_200", 
            myVolume())
    ]
Esempio n. 4
0
def OnEveryDt(interval, source):
    """ Creates an indicator that is updated regularly
    interval - constant interval between updates
    source - function to obtain indicator value
    """

    return IndicatorBase(scheduler.Timer(mathutils.constant(interval)), source, {"smooth": True})
Esempio n. 5
0
    def __init__(self, world, graph_renderer):
        
        self.world = world 
        self.book_A = orderbook.Local(tickSize=0.01, label="A")
        self.book_B = orderbook.Local(tickSize=0.01, label="B")
        
        delay = mathutils.constant(1.07)

        self.link_A = remote.TwoWayLink(remote.Link(delay), remote.Link(delay))
        self.link_B = remote.TwoWayLink(remote.Link(delay), remote.Link(delay))

        self.remote_A = orderbook.Remote(self.book_A, self.link_A)
        self.remote_B = orderbook.Remote(self.book_B, self.link_B)
    
        self.graph = graph_renderer
        self.price_graph = self.graph("Price")
        self.eff_graph = self.graph("efficiency")
        self.amount_graph = self.graph("amount")
        self.balance_graph = self.graph('balance')
        
        self.graphs = [
                       self.price_graph, 
                       self.eff_graph, 
                       self.amount_graph,
                       self.balance_graph
                       ]
         
        self.books = { 'Asset A' : self.book_A ,
                       'Asset B' : self.book_B , 
                       'Remote A': self.remote_A,
                       'Remote B': self.remote_B }
def Dependency(ctx):

    liqVol = mathutils.product(mathutils.rnd.expovariate(.1), mathutils.constant(2))
    
    ctx.volumeStep = 70

    return [
        ctx.makeTrader_A( 
            strategy.LiquidityProvider(defaultValue=50., volumeDistr=liqVol), 
            "LiquidityProvider_A"),
    
        ctx.makeTrader_B( 
            strategy.LiquidityProvider(defaultValue=150., volumeDistr=liqVol), 
            "LiquidityProvider_B"),
    
        ctx.makeTrader_A(strategy.Dependency(ctx.book_B, factor=2), 
                         "A dependent on B"),
    
        ctx.makeTrader_B(strategy.Dependency(ctx.book_A, factor=.5), 
                         "B dependent on A"),

        ctx.makeTrader_A(strategy.DependencyEx(ctx.book_B, factor=2), 
                         "A dependent on B ex"),
    
        ctx.makeTrader_B(strategy.DependencyEx(ctx.book_A, factor=.5), 
                         "B dependent on A ex")
    ]    
Esempio n. 7
0
def SafeSidePrice(orderBook, side, defaultValue):
    
    return defs(
        NotNoneFloat(
                side_price(_.orderBook, side), 
                NotNoneFloat(
                    last_side_price(_.orderBook, side), 
                    mathutils.constant(defaultValue))),
        { 'orderBook': orderBook })
Esempio n. 8
0
def Noise(ctx):
    
    ctx.volumeStep = 10

    return [
        ctx.makeTrader_A(strategy.LiquidityProvider(
                                volumeDistr=mathutils.constant(2),
                                orderFactoryT=order.WithExpiryFactory(
                                    expirationDistr=mathutils.constant(10))), 
                         "liquidity"),
        
        ctx.makeTrader_A(strategy.Noise(), "noise"),
        
        ctx.makeTrader_A(strategy.Noise(
                             orderFactory = order.AlwaysBestFactory()),
                         "noise_best"),
        
        ctx.makeTrader_A(strategy.NoiseEx(), "noise_ex")
    ]
def MeanReversion(ctx):

    ctx.volumeStep = 40

    alpha = 0.015
    V = 1
    linear_signal = signal.RandomWalk(initialValue=200, 
                                      deltaDistr=const(-1), 
                                      label="200-t")

    demo = ctx.addGraph('demo')
    myVolume = lambda: [(observable.VolumeTraded(), demo)]
    myAverage = lambda: [(observable.avg(observable.Price(orderbook.OfTrader()), alpha), demo)]
    myPrice = lambda: [(observable.Price(orderbook.OfTrader()), demo)]

    return [
        ctx.makeTrader_A( 
                       strategy.LiquidityProvider(
                            volumeDistr=const(V*20), 
                            orderFactoryT=order.WithExpiryFactory(
                                expirationDistr=const(10))),
                       label="liquidity"),
    
        ctx.makeTrader_A(strategy.Signal(linear_signal, 
                                         volumeDistr = const(V*3)), 
                         "signal", 
                         [(linear_signal, ctx.amount_graph)]),
    
        ctx.makeTrader_A(strategy.MeanReversion(
                                average=mathutils.ewma(alpha),
                                creationIntervalDistr = mathutils.constant(1.),
                                volumeDistr = const(V)),
                         "meanreversion", 
                         myVolume() + myAverage() + myPrice()),
    
        ctx.makeTrader_A(strategy.MeanReversionEx(
                                average=mathutils.ewma(alpha),
                                creationIntervalDistr = mathutils.constant(1.),
                                volumeDistr = const(V)),
                         "meanreversion_ex", 
                         myVolume())
    ]    
def TrendFollower(ctx):

    V = 1
    alpha = 0.015
    ctx.volumeStep = 30

    linear_signal = signal.RandomWalk(initialValue=200, 
                                      deltaDistr=const(-1), 
                                      label="200-t")
    
    demo = ctx.addGraph('demo')
    myVolume = lambda: [(observable.VolumeTraded(), demo)]
    myAverage = lambda alpha: [(observable.avg(observable.Price(orderbook.OfTrader()), alpha), demo)]
    
    return [
            ctx.makeTrader_A(strategy.LiquidityProvider(
                                volumeDistr=const(V*8), 
                                orderFactoryT=order.WithExpiryFactory(
                                    expirationDistr=const(100))),
                             label="liquidity"),
    
            ctx.makeTrader_A(strategy.Signal(linear_signal, 
                                             volumeDistr = const(V*2)), 
                            "signal", 
                            [
                             (linear_signal, ctx.amount_graph)
                            ]),
    
            ctx.makeTrader_A(strategy.TrendFollower(
                                    creationIntervalDistr = mathutils.constant(1.),
                                    average=mathutils.ewma(alpha),
                                    volumeDistr = const(V)),
                             "trendfollower", 
                             myVolume() + myAverage(alpha)),
            
            ctx.makeTrader_A(strategy.TrendFollowerEx(
                                       creationIntervalDistr = mathutils.constant(1.),
                                       average=mathutils.ewma(alpha),
                                       volumeDistr = const(V)),
                             "trendfollower_ex",
                             myVolume())
    ]
Esempio n. 11
0
def FundamentalValueEx(fundamentalValue      = mathutils.constant(100.),
                       orderFactory          = order.MarketFactory, 
                       volumeDistr           = mathutils.rnd.expovariate(1.), 
                       creationIntervalDistr = mathutils.rnd.expovariate(1.)):
    
    orderBook = orderbook.OfTrader()
    r = Generic(orderFactory= orderFactory, 
                volumeFunc  = volumeDistr, 
                eventGen    = scheduler.Timer(creationIntervalDistr), 
                sideFunc    = FundamentalValueSide(orderBook, fundamentalValue))
    
    return r
Esempio n. 12
0
def RSI(ctx):

    const = mathutils.constant
    linear_signal = signal.RandomWalk(initialValue=20, 
                                      deltaDistr=const(-.1), 
                                      label="20-0.1t")
    
    one = mathutils.constant(1)
    
    rsi = observable.OnEveryDt(one.value, 
                         observable.Fold(
                            observable.Price(
                                orderbook.OfTrader()), 
                            mathutils.rsi()))
    
    threshold = 30
    
    demo = ctx.addGraph('demo')
    myVolume = lambda: [(observable.VolumeTraded(), demo)]
    myRsi = lambda: [(rsi, demo)]
    
    alpha = 1./14
    
    myRsiBis = lambda: [(observable.OnEveryDt(1, 
                            observable.RSI(orderbook.OfTrader(), 
                                           0, 
                                           alpha)), 
                         demo)]
    
    return [
        ctx.makeTrader_A(strategy.LiquidityProvider(volumeDistr=const(4)), "liquidity"),
        
        ctx.makeTrader_A(strategy.Signal(linear_signal), "signal", 
                         [(linear_signal, ctx.amount_graph)]),
    
        ctx.makeTrader_A(strategy.RSIbis(alpha = alpha,
                                         timeframe = 0,
                                         threshold=threshold, 
                                         volumeDistr=one, 
                                         creationIntervalDistr=one),
                         "rsi_bis",
                         myVolume() + myRsiBis()), 
            
        ctx.makeTrader_A(strategy.RSIEx(alpha = alpha,
                                        threshold=threshold, 
                                        volumeDistr=one, 
                                        creationIntervalDistr=one), 
                         "rsi_ex", (myVolume() + myRsi() + 
                                    Constant(threshold, demo) + 
                                    Constant(100-threshold, demo)))
    ]    
Esempio n. 13
0
def SignalSide(source, threshold = 0):
    
    return defs(ConditionSide(
                    less_float(
                        _.threshold, 
                        _.source), 
                    ConstantSide(Side.Buy), 
                        ConditionSide(
                            less_float(
                                _.source, 
                                mathutils.negate(_.threshold)), 
                            ConstantSide(Side.Sell), 
                            none_side())), 
                { 'source'    : source, 
                  'threshold' : mathutils.constant(threshold) })
Esempio n. 14
0
def RSIbis (timeframe               = 0., 
            threshold               = 30,
            alpha                   = 1./14,
            orderFactory            = order.MarketFactory, 
            volumeDistr             = mathutils.rnd.expovariate(1.), 
            creationIntervalDistr   = mathutils.rnd.expovariate(1.)):
    
    thisBook = orderbook.OfTrader()
    
    return defs(Generic(orderFactory = orderFactory, 
                        volumeFunc   = volumeDistr, 
                        eventGen     = scheduler.Timer(creationIntervalDistr),
                        sideFunc     = SignalSide(mathutils.sub(mathutils.constant(50), 
                                                                _.rsi), 
                                                  50-threshold)), 
                { 'rsi' : observable.RSI(thisBook, timeframe, alpha) })
Esempio n. 15
0
def Arbitrage(ctx):

    liqVol = mathutils.product(mathutils.rnd.expovariate(.1), mathutils.constant(2))
    
    ctx.volumeStep = 70

    return [
        ctx.makeTrader_A( 
            strategy.LiquidityProvider(defaultValue=50., volumeDistr=liqVol), 
            "LiquidityProvider_A"),
    
        ctx.makeTrader_B( 
            strategy.LiquidityProvider(defaultValue=150., volumeDistr=liqVol), 
            "LiquidityProvider_B"),
            
        ctx.makeMultiAssetTrader([ctx.remote_A, ctx.remote_B], strategy.Arbitrage(), "Arbitrager")
    ]    
Esempio n. 16
0
def DependencyEx      (bookToDependOn,
                       factor                = mathutils.constant(1.),
                       orderFactory          = order.MarketFactory, 
                       volumeDistr           = mathutils.rnd.expovariate(1.)):

    orderBook = orderbook.OfTrader()

    r = defs(
        Generic(orderFactory= orderFactory, 
                volumeFunc  = volumeDistr, 
                eventGen    = _.dependee, 
                sideFunc    = FundamentalValueSide(orderBook, _.dependee)),
        { 'dependee' : observable.Price(bookToDependOn) })
    
    r._alias = ["Generic", "Dependency"]
    
    return r
Esempio n. 17
0
    def __init__(self):
        
        self._chooseTheBest = bind.Method(self, '_chooseTheBest_impl')
        Strategy.__init__(self) # TODO: eventGen should be a parameter
        self._eventGen = scheduler.Timer(mathutils.constant(1))

        def _createInstance(sp):
            estimator_strategy = self.estimator(sp)
            estimator = trader.SingleAsset(orderbook.OfTrader(trader.ParentProxy()),estimator_strategy)
            efficiency = self.efficiency(estimator)
            
            return (sp, estimator, estimator_strategy, efficiency)
        
        self._strategies = [_createInstance(sp) for sp in self.strategies]
        
        self._chooseTheBest = bind.Method(self, '_chooseTheBest_impl')
        self._current = None
        event.subscribe(self._eventGen, self._chooseTheBest, self)
    def __init__(self):

        Strategy.__init__(self)  # TODO: eventGen should be a parameter
        self._eventGen = scheduler.Timer(mathutils.constant(1))

        def _createInstance(sp):
            estimator_strategy = self.estimator(sp)
            estimator = trader.SingleAsset(orderbook.OfTrader(trader.ParentProxy()), estimator_strategy)
            efficiency = self.efficiency(estimator)

            return (sp, estimator, estimator_strategy, efficiency)

        self._strategies = [_createInstance(sp) for sp in self.strategies]

        self._choose = bind.Method(self, "_choose_impl")
        self._strategyWeights = self.weight
        self._current = None
        # what is the data source for weight update?
        event.subscribe(self._eventGen, self._choose, self)

        # suspend all strategies
        for (s, _, _, _) in self._strategies:
            s.suspend(True)
Esempio n. 19
0
 def __init__(self, orderFactory = LimitFactory, priceFunc = mathutils.constant(100)):
     self.orderFactory = orderFactory
     self.priceFunc = priceFunc
Esempio n. 20
0
 def __init__(self, latency=mathutils.constant(0.001)):
     """ Initializes the link with a latency function
     """
     self._scheduler = scheduler.current() 
     self.latency = latency
     self.reset()
Esempio n. 21
0
def Constant(c, demo):
    return [(observable.OnEveryDt(10, mathutils.constant(c)), demo)]
Esempio n. 22
0
 def __init__(self, expirationDistr=mathutils.constant(10), orderFactory = LimitFactory):
     self.expirationDistr = expirationDistr
     self.orderFactory = orderFactory
def virtualWithUnitVolume(strategy):
    """ Creates for a *strategy* a clone with same parameters but sending virtual market orders of unit volume
    """
    return strategy.With(volumeDistr=mathutils.constant(1), orderFactory=order.VirtualMarketFactory)    
Esempio n. 24
0
def PriceAtVolume(interval, orderbook, side, volume):

    return IndicatorBase(scheduler.Timer(mathutils.constant(interval)),
                         price_at_volume(orderbook, side, volume), 
                         {'smooth':True, 'fillBelow' : side == Side.Buy, 'fillAbove' : side == Side.Sell})
Esempio n. 25
0
def VolumeLevels(interval, orderbook, side, volumeDelta, volumeCount):

    return IndicatorBase(scheduler.Timer(mathutils.constant(interval)),
                         volume_levels(orderbook, side, volumeDelta, volumeCount), 
                         {'smooth':True, 'volumeLevels' : True, 
                          'fillBelow' : side == Side.Buy, 'fillAbove' : side == Side.Sell})