Esempio n. 1
0
class Account_Impl(Account_Base):
    def __init__(self):
        event.subscribe(self.inner.on_order_created,
                        _(self).onOrderCreated, self)
        event.subscribe(OnOrderMatched(), _(self)._onOrderMatched, self)
        from marketsim.gen._out.event._event import Event
        self.on_traded = Event()
        self.orderBook = OfTrader()
        self._balance = 0
        self._position = 0

    _internals = ["orderBook"]

    def _onOrderMatched(self, trader, order, price, volume):
        if getattr(order, '_strategy', None) == self.inner:
            pv = price * volume
            self._balance += pv if order.side == Side.Sell else -pv
            self._position += volume if order.side == Side.Buy else -volume
            self.on_traded.fire(self)

    @property
    def amount(self):
        return self._position

    @property
    def PnL(self):
        return self._balance

    def onOrderCreated(self, order, source):
        order._strategy = source
Esempio n. 2
0
class Account_Impl(Account_Base):
    
    def __init__(self):
        event.subscribe(self.inner.on_order_created, _(self).onOrderCreated, self)
        event.subscribe(OnOrderMatched(), _(self)._onOrderMatched, self)
        from marketsim.gen._out.event._event import Event
        self.on_traded = Event()
        self.orderBook = OfTrader()
        self._balance = 0
        self._position = 0
        
    _internals = ["orderBook"]
        
    def _onOrderMatched(self, trader, order, price, volume):
        if getattr(order, '_strategy', None) == self.inner:
            pv = price * volume
            self._balance += pv if order.side == Side.Sell else -pv
            self._position += volume if order.side == Side.Buy else -volume
            self.on_traded.fire(self)
    
    @property
    def amount(self):
        return self._position
    
    @property
    def PnL(self):
        return self._balance
    
    def onOrderCreated(self, order, source):
        order._strategy = source
Esempio n. 3
0
 def __init__(self):
     event.subscribe(self.inner.on_order_created,
                     _(self).onOrderCreated, self)
     event.subscribe(OnOrderMatched(), _(self)._onOrderMatched, self)
     from marketsim.gen._out.event._event import Event
     self.on_traded = Event()
     self.orderBook = OfTrader()
     self._balance = 0
     self._position = 0
Esempio n. 4
0
    def __init__(self, x=None):
        from marketsim.gen._out.strategy.price._marketdata import MarketData_StringStringStringFloatFloat as _strategy_price_MarketData_StringStringStringFloatFloat
        from marketsim.gen._out.event._event import Event
        from marketsim import _
        from marketsim import event
        from marketsim import deref_opt
        self.x = x if x is not None else deref_opt(
            _strategy_price_MarketData_StringStringStringFloatFloat())
        self.impl = self.getImpl()

        self.on_order_created = Event()
        event.subscribe(self.impl.on_order_created, _(self)._send, self)
Esempio n. 5
0
 def __init__(self, inner = None, lossFactor = None):
     from marketsim.gen._out._const import const_Float as _const_Float
     from marketsim.gen._out.strategy.price._laddermm import LadderMM_SideFloatIObservableIOrderInt as _strategy_price_LadderMM_SideFloatIObservableIOrderInt
     from marketsim.gen._out.event._event import Event
     from marketsim import _
     from marketsim import event
     from marketsim import deref_opt
     self.inner = inner if inner is not None else deref_opt(_strategy_price_LadderMM_SideFloatIObservableIOrderInt())
     self.lossFactor = lossFactor if lossFactor is not None else deref_opt(_const_Float(0.2))
     self.impl = self.getImpl()
     
     self.on_order_created = Event()
     event.subscribe(self.impl.on_order_created, _(self)._send, self)
Esempio n. 6
0
class Strategy(Base):
    
    def __init__(self):
        Base.__init__(self)
        from marketsim.gen._out.event._event import Event
        self.on_order_created = Event()

    def _send(self, order, unused = None):
        self.on_order_created.fire(order, self)

    @property
    def orderBook(self):
        return self.trader.orderBook
Esempio n. 7
0
    def __init__(self, x=None, side=None, sign=None):
        from marketsim.gen._out.side._sell import Sell_ as _side_Sell_
        from marketsim.gen._out.event._event import Event
        from marketsim import _
        from marketsim import event
        from marketsim.gen._out.strategy.price._marketmaker import MarketMaker_FloatFloat as _strategy_price_MarketMaker_FloatFloat
        from marketsim import deref_opt
        self.x = x if x is not None else deref_opt(
            _strategy_price_MarketMaker_FloatFloat())
        self.side = side if side is not None else deref_opt(_side_Sell_())
        self.sign = sign if sign is not None else 1.0
        self.impl = self.getImpl()

        self.on_order_created = Event()
        event.subscribe(self.impl.on_order_created, _(self)._send, self)
Esempio n. 8
0
    def __init__(self, x=None, orderFactory=None):
        from marketsim.gen._out.event._event import Event
        from marketsim import _
        from marketsim.gen._out.strategy.position._bollinger_linear import Bollinger_linear_FloatIObservableFloatISingleAssetTrader as _strategy_position_Bollinger_linear_FloatIObservableFloatISingleAssetTrader
        from marketsim import event
        from marketsim.gen._out.order._curried._signedvolume_marketsigned import signedVolume_MarketSigned_ as _order__curried_signedVolume_MarketSigned_
        from marketsim import deref_opt
        self.x = x if x is not None else deref_opt(
            _strategy_position_Bollinger_linear_FloatIObservableFloatISingleAssetTrader(
            ))
        self.orderFactory = orderFactory if orderFactory is not None else deref_opt(
            _order__curried_signedVolume_MarketSigned_())
        self.impl = self.getImpl()

        self.on_order_created = Event()
        event.subscribe(self.impl.on_order_created, _(self)._send, self)
Esempio n. 9
0
 def __init__(self):
     event.subscribe(self.inner.on_order_created, _(self).onOrderCreated, self)
     event.subscribe(OnOrderMatched(), _(self)._onOrderMatched, self)
     from marketsim.gen._out.event._event import Event
     self.on_traded = Event()
     self.orderBook = OfTrader()
     self._balance = 0
     self._position = 0
Esempio n. 10
0
    def __init__(self, inner=None, account=None, performance=None):
        from marketsim.gen._out.strategy.account.inner._inner_virtualmarket import inner_VirtualMarket_ as _strategy_account_inner_inner_VirtualMarket_
        from marketsim.gen._out.event._event import Event
        from marketsim import _
        from marketsim import event
        from marketsim.gen._out.strategy._empty import Empty_ as _strategy_Empty_
        from marketsim.gen._out.strategy.weight.trader._trader_traderefficiencytrend import trader_TraderEfficiencyTrend_Float as _strategy_weight_trader_trader_TraderEfficiencyTrend_Float
        from marketsim import deref_opt
        self.inner = inner if inner is not None else deref_opt(
            _strategy_Empty_())
        self.account = account if account is not None else deref_opt(
            _strategy_account_inner_inner_VirtualMarket_())
        self.performance = performance if performance is not None else deref_opt(
            _strategy_weight_trader_trader_TraderEfficiencyTrend_Float())
        self.impl = self.getImpl()

        self.on_order_created = Event()
        event.subscribe(self.impl.on_order_created, _(self)._send, self)
Esempio n. 11
0
 def __init__(self):
     Holder_Impl.__init__(self)
     # event to be fired when an order has been sent
     from marketsim.gen._out.event._event import Event
     self.on_order_sent = Event()
     # event to be fired when an order issued by the trader has been matched
     self.on_order_matched = Event()
     # event to be fired when an order issued by the trader has been cancelled
     self.on_order_disposed = Event()
     # event to be fired when a trader's is traded; to be removed
     self.on_traded = Event()
     self.reset()
Esempio n. 12
0
    def __init__(self, x=None, eventGen=None, orderFactory=None):
        from marketsim.gen._out.event._every import Every_Float as _event_Every_Float
        from marketsim.gen._out.math.random._expovariate import expovariate_Float as _math_random_expovariate_Float
        from marketsim.gen._out.event._event import Event
        from marketsim import _
        from marketsim import event
        from marketsim.gen._out.strategy.price._liquidityprovider import LiquidityProvider_FloatFloatIOrderBook as _strategy_price_LiquidityProvider_FloatFloatIOrderBook
        from marketsim.gen._out.order._curried._sideprice_limit import sideprice_Limit_Float as _order__curried_sideprice_Limit_Float
        from marketsim import deref_opt
        self.x = x if x is not None else deref_opt(
            _strategy_price_LiquidityProvider_FloatFloatIOrderBook())
        self.eventGen = eventGen if eventGen is not None else deref_opt(
            _event_Every_Float(deref_opt(_math_random_expovariate_Float(1.0))))
        self.orderFactory = orderFactory if orderFactory is not None else deref_opt(
            _order__curried_sideprice_Limit_Float())
        self.impl = self.getImpl()

        self.on_order_created = Event()
        event.subscribe(self.impl.on_order_created, _(self)._send, self)
Esempio n. 13
0
 def __init__(self, x = None):
     from marketsim.gen._out.event._event import Event
     from marketsim import _
     from marketsim import event
     from marketsim.gen._out.strategy.price._marketmaker import MarketMaker_FloatFloat as _strategy_price_MarketMaker_FloatFloat
     from marketsim import deref_opt
     self.x = x if x is not None else deref_opt(_strategy_price_MarketMaker_FloatFloat())
     self.impl = self.getImpl()
     
     self.on_order_created = Event()
     event.subscribe(self.impl.on_order_created, _(self)._send, self)
Esempio n. 14
0
    def __init__(self):

        # orders created by trader
        from marketsim.gen._out.trader._singleproxy import SingleProxy
        from marketsim.gen._out.orderbook._oftrader import OfTrader
        self._elements = []
        self._eventGen = event.Every(self.cancellationIntervalDistr)
        self._myTrader = SingleProxy()
        self._book = OfTrader(self._myTrader)
        from marketsim.gen._out.event._event import Event
        self.on_order_created = Event()
Esempio n. 15
0
 def __init__(self, x = None, orderFactory = None):
     from marketsim.gen._out.strategy.position._rsi_linear import RSI_linear_FloatIObservableFloatFloatISingleAssetTrader as _strategy_position_RSI_linear_FloatIObservableFloatFloatISingleAssetTrader
     from marketsim.gen._out.event._event import Event
     from marketsim import _
     from marketsim import event
     from marketsim.gen._out.order._curried._signedvolume_marketsigned import signedVolume_MarketSigned_ as _order__curried_signedVolume_MarketSigned_
     from marketsim import deref_opt
     self.x = x if x is not None else deref_opt(_strategy_position_RSI_linear_FloatIObservableFloatFloatISingleAssetTrader())
     self.orderFactory = orderFactory if orderFactory is not None else deref_opt(_order__curried_signedVolume_MarketSigned_())
     self.impl = self.getImpl()
     
     self.on_order_created = Event()
     event.subscribe(self.impl.on_order_created, _(self)._send, self)
Esempio n. 16
0
 def __init__(self, x = None, side = None, sign = None):
     from marketsim.gen._out.strategy.price._marketdata import MarketData_StringStringStringFloatFloat as _strategy_price_MarketData_StringStringStringFloatFloat
     from marketsim.gen._out.side._sell import Sell_ as _side_Sell_
     from marketsim.gen._out.event._event import Event
     from marketsim import _
     from marketsim import event
     from marketsim import deref_opt
     self.x = x if x is not None else deref_opt(_strategy_price_MarketData_StringStringStringFloatFloat())
     self.side = side if side is not None else deref_opt(_side_Sell_())
     self.sign = sign if sign is not None else 1.0
     self.impl = self.getImpl()
     
     self.on_order_created = Event()
     event.subscribe(self.impl.on_order_created, _(self)._send, self)
 def __init__(self, inner = None, account = None, performance = None):
     from marketsim.gen._out.strategy.account.inner._inner_virtualmarket import inner_VirtualMarket_ as _strategy_account_inner_inner_VirtualMarket_
     from marketsim.gen._out.event._event import Event
     from marketsim import _
     from marketsim import event
     from marketsim.gen._out.strategy._empty import Empty_ as _strategy_Empty_
     from marketsim.gen._out.strategy.weight.trader._trader_traderefficiencytrend import trader_TraderEfficiencyTrend_Float as _strategy_weight_trader_trader_TraderEfficiencyTrend_Float
     from marketsim import deref_opt
     self.inner = inner if inner is not None else deref_opt(_strategy_Empty_())
     self.account = account if account is not None else deref_opt(_strategy_account_inner_inner_VirtualMarket_())
     self.performance = performance if performance is not None else deref_opt(_strategy_weight_trader_trader_TraderEfficiencyTrend_Float())
     self.impl = self.getImpl()
     
     self.on_order_created = Event()
     event.subscribe(self.impl.on_order_created, _(self)._send, self)
Esempio n. 18
0
 def __init__(self, x = None, eventGen = None, orderFactory = None):
     from marketsim.gen._out.event._every import Every_Float as _event_Every_Float
     from marketsim.gen._out.math.random._expovariate import expovariate_Float as _math_random_expovariate_Float
     from marketsim.gen._out.event._event import Event
     from marketsim import _
     from marketsim import event
     from marketsim.gen._out.strategy.price._liquidityprovider import LiquidityProvider_FloatFloatIOrderBook as _strategy_price_LiquidityProvider_FloatFloatIOrderBook
     from marketsim.gen._out.order._curried._sideprice_limit import sideprice_Limit_Float as _order__curried_sideprice_Limit_Float
     from marketsim import deref_opt
     self.x = x if x is not None else deref_opt(_strategy_price_LiquidityProvider_FloatFloatIOrderBook())
     self.eventGen = eventGen if eventGen is not None else deref_opt(_event_Every_Float(deref_opt(_math_random_expovariate_Float(1.0))))
     self.orderFactory = orderFactory if orderFactory is not None else deref_opt(_order__curried_sideprice_Limit_Float())
     self.impl = self.getImpl()
     
     self.on_order_created = Event()
     event.subscribe(self.impl.on_order_created, _(self)._send, self)
Esempio n. 19
0
class StopLoss_ISuspendableStrategyIObservableFloat(ISingleAssetStrategy):
    """ 
    """ 
    def __init__(self, inner = None, lossFactor = None):
        from marketsim.gen._out._const import const_Float as _const_Float
        from marketsim.gen._out.strategy.price._laddermm import LadderMM_SideFloatIObservableIOrderInt as _strategy_price_LadderMM_SideFloatIObservableIOrderInt
        from marketsim.gen._out.event._event import Event
        from marketsim import _
        from marketsim import event
        from marketsim import deref_opt
        self.inner = inner if inner is not None else deref_opt(_strategy_price_LadderMM_SideFloatIObservableIOrderInt())
        self.lossFactor = lossFactor if lossFactor is not None else deref_opt(_const_Float(0.2))
        self.impl = self.getImpl()
        
        self.on_order_created = Event()
        event.subscribe(self.impl.on_order_created, _(self)._send, self)
    
    @property
    def label(self):
        return repr(self)
    
    _properties = {
        'inner' : ISuspendableStrategy,
        'lossFactor' : IObservablefloat
    }
    
    
    
    
    def __repr__(self):
        return "StopLoss(%(inner)s, %(lossFactor)s)" % dict([ (name, getattr(self, name)) for name in self._properties.iterkeys() ])
    
    def bind_ex(self, ctx):
        if self.__dict__.get('_bound_ex', False): return
        self.__dict__['_bound_ex'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        self.__dict__['_ctx_ex'] = ctx.updatedFrom(self)
        self.inner.bind_ex(self._ctx_ex)
        self.lossFactor.bind_ex(self._ctx_ex)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions: s.bind_ex(self.__dict__['_ctx_ex'])
        self.impl.bind_ex(self.__dict__['_ctx_ex'])
        self.__dict__['_processing_ex'] = False
    
    def reset_ex(self, generation):
        if self.__dict__.get('_reset_generation_ex', -1) == generation: return
        self.__dict__['_reset_generation_ex'] = generation
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        
        self.inner.reset_ex(generation)
        self.lossFactor.reset_ex(generation)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions: s.reset_ex(generation)
        self.impl.reset_ex(generation)
        self.__dict__['_processing_ex'] = False
    
    def typecheck(self):
        from marketsim import rtti
        from marketsim.gen._out._isuspendablestrategy import ISuspendableStrategy
        from marketsim.gen._out._iobservable._iobservablefloat import IObservablefloat
        rtti.typecheck(ISuspendableStrategy, self.inner)
        rtti.typecheck(IObservablefloat, self.lossFactor)
    
    def registerIn(self, registry):
        if self.__dict__.get('_id', False): return
        self.__dict__['_id'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        registry.insert(self)
        self.inner.registerIn(registry)
        self.lossFactor.registerIn(registry)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions: s.registerIn(registry)
        self.impl.registerIn(registry)
        self.__dict__['_processing_ex'] = False
    
    def bind(self, ctx):
        self._ctx = ctx.clone()
    
    _internals = ['impl']
    def __call__(self, *args, **kwargs):
        return self.impl()
    
    def reset(self):
        from marketsim import context
        self.impl = self.getImpl()
        ctx_ex = getattr(self, '_ctx_ex', None)
        if ctx_ex: self.impl.bind_ex(ctx_ex)
        
    
    def getImpl(self):
        from marketsim.gen._out.strategy.price._clearable import Clearable_ISuspendableStrategyBoolean as _strategy_price_Clearable_ISuspendableStrategyBoolean
        from marketsim.gen._out.strategy.price._islosstoohigh import isLossTooHigh_IObservableFloat as _strategy_price_isLossTooHigh_IObservableFloat
        from marketsim import deref_opt
        return deref_opt(_strategy_price_Clearable_ISuspendableStrategyBoolean(self.inner,deref_opt(_strategy_price_isLossTooHigh_IObservableFloat(self.lossFactor))))
    
    def __getattr__(self, name):
        if name[0:2] != '__' and self.impl:
            return getattr(self.impl, name)
        else:
            raise AttributeError
    
    @property
    def suspended(self):
        return self.inner.suspended
    
    def set_suspended(self, value):
        self.inner.suspended = value
    
    def _send(self, order, source):
        self.on_order_created.fire(order, self)
class TradeIfProfitable_ISingleAssetStrategyISingleAssetStrategyIAccountIAccountFloat(ISingleAssetStrategy):
    """ **Adaptive strategy that evaluates *inner* strategy efficiency**
    
      and if it is considered as good, sends orders
    
    Parameters are:
    
    **inner**
    	 wrapped strategy 
    
    **account**
    	 defines how strategy trades are booked:
    	 actually traded amount or virtual market orders are
    	 used in order to estimate how the strategy would have traded
    	 if all its orders appeared at market 
    
    **performance**
    	 given a trading account tells
    	 should it be considered as effective or not 
    """ 
    def __init__(self, inner = None, account = None, performance = None):
        from marketsim.gen._out.strategy.account.inner._inner_virtualmarket import inner_VirtualMarket_ as _strategy_account_inner_inner_VirtualMarket_
        from marketsim.gen._out.event._event import Event
        from marketsim import _
        from marketsim import event
        from marketsim.gen._out.strategy._empty import Empty_ as _strategy_Empty_
        from marketsim.gen._out.strategy.weight.trader._trader_traderefficiencytrend import trader_TraderEfficiencyTrend_Float as _strategy_weight_trader_trader_TraderEfficiencyTrend_Float
        from marketsim import deref_opt
        self.inner = inner if inner is not None else deref_opt(_strategy_Empty_())
        self.account = account if account is not None else deref_opt(_strategy_account_inner_inner_VirtualMarket_())
        self.performance = performance if performance is not None else deref_opt(_strategy_weight_trader_trader_TraderEfficiencyTrend_Float())
        self.impl = self.getImpl()
        
        self.on_order_created = Event()
        event.subscribe(self.impl.on_order_created, _(self)._send, self)
    
    @property
    def label(self):
        return repr(self)
    
    _properties = {
        'inner' : ISingleAssetStrategy,
        'account' : IFunctionIAccount_from_ISingleAssetStrategy,
        'performance' : IFunctionIFunctionfloat_from_IAccount
    }
    
    
    
    
    
    
    def __repr__(self):
        return "TradeIfProfitable(%(inner)s, %(account)s, %(performance)s)" % dict([ (name, getattr(self, name)) for name in self._properties.iterkeys() ])
    
    def bind_ex(self, ctx):
        if self.__dict__.get('_bound_ex', False): return
        self.__dict__['_bound_ex'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        self.__dict__['_ctx_ex'] = ctx.updatedFrom(self)
        self.inner.bind_ex(self._ctx_ex)
        self.account.bind_ex(self._ctx_ex)
        self.performance.bind_ex(self._ctx_ex)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions: s.bind_ex(self.__dict__['_ctx_ex'])
        self.impl.bind_ex(self.__dict__['_ctx_ex'])
        self.__dict__['_processing_ex'] = False
    
    def reset_ex(self, generation):
        if self.__dict__.get('_reset_generation_ex', -1) == generation: return
        self.__dict__['_reset_generation_ex'] = generation
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        
        self.inner.reset_ex(generation)
        self.account.reset_ex(generation)
        self.performance.reset_ex(generation)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions: s.reset_ex(generation)
        self.impl.reset_ex(generation)
        self.__dict__['_processing_ex'] = False
    
    def typecheck(self):
        from marketsim import rtti
        from marketsim.gen._out._isingleassetstrategy import ISingleAssetStrategy
        from marketsim.gen._out._ifunction._ifunctioniaccount_from_isingleassetstrategy import IFunctionIAccount_from_ISingleAssetStrategy
        from marketsim.gen._out._ifunction._ifunctionifunctionfloat_from_iaccount import IFunctionIFunctionfloat_from_IAccount
        rtti.typecheck(ISingleAssetStrategy, self.inner)
        rtti.typecheck(IFunctionIAccount_from_ISingleAssetStrategy, self.account)
        rtti.typecheck(IFunctionIFunctionfloat_from_IAccount, self.performance)
    
    def registerIn(self, registry):
        if self.__dict__.get('_id', False): return
        self.__dict__['_id'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        registry.insert(self)
        self.inner.registerIn(registry)
        self.account.registerIn(registry)
        self.performance.registerIn(registry)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions: s.registerIn(registry)
        self.impl.registerIn(registry)
        self.__dict__['_processing_ex'] = False
    
    def bind(self, ctx):
        self._ctx = ctx.clone()
    
    _internals = ['impl']
    def __call__(self, *args, **kwargs):
        return self.impl()
    
    def reset(self):
        from marketsim import context
        self.impl = self.getImpl()
        ctx_ex = getattr(self, '_ctx_ex', None)
        if ctx_ex: self.impl.bind_ex(ctx_ex)
        
    
    def getImpl(self):
        from marketsim.gen._out.strategy._suspendable import Suspendable_ISingleAssetStrategyBoolean as _strategy_Suspendable_ISingleAssetStrategyBoolean
        from marketsim.gen._out.ops._greaterequal import GreaterEqual_FloatFloat as _ops_GreaterEqual_FloatFloat
        from marketsim import deref_opt
        from marketsim.gen._out._constant import constant_Int as _constant_Int
        return deref_opt(_strategy_Suspendable_ISingleAssetStrategyBoolean(self.inner,deref_opt(_ops_GreaterEqual_FloatFloat(deref_opt(self.performance(deref_opt(self.account(self.inner)))),deref_opt(_constant_Int(0))))))
    
    def __getattr__(self, name):
        if name[0:2] != '__' and self.impl:
            return getattr(self.impl, name)
        else:
            raise AttributeError
    
    @property
    def suspended(self):
        return self.inner.suspended
    
    def set_suspended(self, value):
        self.inner.suspended = value
    
    def _send(self, order, source):
        self.on_order_created.fire(order, self)
Esempio n. 21
0
class Strategy_strategypositionRSI_linearFloatIObservableIOrder(
        ISingleAssetStrategy):
    """ 
    """
    def __init__(self, x=None, orderFactory=None):
        from marketsim.gen._out.strategy.position._rsi_linear import RSI_linear_FloatIObservableFloatFloatISingleAssetTrader as _strategy_position_RSI_linear_FloatIObservableFloatFloatISingleAssetTrader
        from marketsim.gen._out.event._event import Event
        from marketsim import _
        from marketsim import event
        from marketsim.gen._out.order._curried._signedvolume_marketsigned import signedVolume_MarketSigned_ as _order__curried_signedVolume_MarketSigned_
        from marketsim import deref_opt
        self.x = x if x is not None else deref_opt(
            _strategy_position_RSI_linear_FloatIObservableFloatFloatISingleAssetTrader(
            ))
        self.orderFactory = orderFactory if orderFactory is not None else deref_opt(
            _order__curried_signedVolume_MarketSigned_())
        self.impl = self.getImpl()

        self.on_order_created = Event()
        event.subscribe(self.impl.on_order_created, _(self)._send, self)

    @property
    def label(self):
        return repr(self)

    _properties = {
        'x': RSI_linear,
        'orderFactory': IFunctionIObservableIOrder_from_IFunctionfloat
    }

    def __repr__(self):
        return "RSI_linear(%(x)s, %(orderFactory)s)" % dict(
            [(name, getattr(self, name))
             for name in self._properties.iterkeys()])

    def bind_ex(self, ctx):
        if self.__dict__.get('_bound_ex', False): return
        self.__dict__['_bound_ex'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        self.__dict__['_ctx_ex'] = ctx.updatedFrom(self)
        self.x.bind_ex(self._ctx_ex)
        self.orderFactory.bind_ex(self._ctx_ex)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions:
                s.bind_ex(self.__dict__['_ctx_ex'])
        self.impl.bind_ex(self.__dict__['_ctx_ex'])
        self.__dict__['_processing_ex'] = False

    def reset_ex(self, generation):
        if self.__dict__.get('_reset_generation_ex', -1) == generation: return
        self.__dict__['_reset_generation_ex'] = generation
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True

        self.x.reset_ex(generation)
        self.orderFactory.reset_ex(generation)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions:
                s.reset_ex(generation)
        self.impl.reset_ex(generation)
        self.__dict__['_processing_ex'] = False

    def typecheck(self):
        from marketsim import rtti
        from marketsim.gen._out.strategy.position._rsi_linear import RSI_linear
        from marketsim.gen._out._ifunction._ifunctioniobservableiorder_from_ifunctionfloat import IFunctionIObservableIOrder_from_IFunctionfloat
        rtti.typecheck(RSI_linear, self.x)
        rtti.typecheck(IFunctionIObservableIOrder_from_IFunctionfloat,
                       self.orderFactory)

    def registerIn(self, registry):
        if self.__dict__.get('_id', False): return
        self.__dict__['_id'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        registry.insert(self)
        self.x.registerIn(registry)
        self.orderFactory.registerIn(registry)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions:
                s.registerIn(registry)
        self.impl.registerIn(registry)
        self.__dict__['_processing_ex'] = False

    def bind(self, ctx):
        self._ctx = ctx.clone()

    _internals = ['impl']

    def __call__(self, *args, **kwargs):
        return self.impl()

    def reset(self):
        from marketsim import context
        self.impl = self.getImpl()
        ctx_ex = getattr(self, '_ctx_ex', None)
        if ctx_ex: self.impl.bind_ex(ctx_ex)

    def getImpl(self):
        from marketsim.gen._out.strategy._generic import Generic_IObservableIOrderIEvent as _strategy_Generic_IObservableIOrderIEvent
        from marketsim.gen._out.strategy.position._position import Position_strategypositionRSI_linear as _strategy_position_Position_strategypositionRSI_linear
        from marketsim import deref_opt
        return deref_opt(
            _strategy_Generic_IObservableIOrderIEvent(
                deref_opt(
                    self.orderFactory(
                        deref_opt(
                            _strategy_position_Position_strategypositionRSI_linear(
                                self.x))))))

    def __getattr__(self, name):
        if name[0:2] != '__' and self.impl:
            return getattr(self.impl, name)
        else:
            raise AttributeError

    @property
    def suspended(self):
        return self.inner.suspended

    def set_suspended(self, value):
        self.inner.suspended = value

    def _send(self, order, source):
        self.on_order_created.fire(order, self)
Esempio n. 22
0
class TwoSides_strategypriceMarketMaker(ISingleAssetStrategy):
    """ 
    """
    def __init__(self, x=None):
        from marketsim.gen._out.event._event import Event
        from marketsim import _
        from marketsim import event
        from marketsim.gen._out.strategy.price._marketmaker import MarketMaker_FloatFloat as _strategy_price_MarketMaker_FloatFloat
        from marketsim import deref_opt
        self.x = x if x is not None else deref_opt(
            _strategy_price_MarketMaker_FloatFloat())
        self.impl = self.getImpl()

        self.on_order_created = Event()
        event.subscribe(self.impl.on_order_created, _(self)._send, self)

    @property
    def label(self):
        return repr(self)

    _properties = {'x': MarketMaker}

    def __repr__(self):
        return "MarketMaker(%(x)s)" % dict([(name, getattr(
            self, name)) for name in self._properties.iterkeys()])

    def bind_ex(self, ctx):
        if self.__dict__.get('_bound_ex', False): return
        self.__dict__['_bound_ex'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        self.__dict__['_ctx_ex'] = ctx.updatedFrom(self)
        self.x.bind_ex(self._ctx_ex)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions:
                s.bind_ex(self.__dict__['_ctx_ex'])
        self.impl.bind_ex(self.__dict__['_ctx_ex'])
        self.__dict__['_processing_ex'] = False

    def reset_ex(self, generation):
        if self.__dict__.get('_reset_generation_ex', -1) == generation: return
        self.__dict__['_reset_generation_ex'] = generation
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True

        self.x.reset_ex(generation)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions:
                s.reset_ex(generation)
        self.impl.reset_ex(generation)
        self.__dict__['_processing_ex'] = False

    def typecheck(self):
        from marketsim import rtti
        from marketsim.gen._out.strategy.price._marketmaker import MarketMaker
        rtti.typecheck(MarketMaker, self.x)

    def registerIn(self, registry):
        if self.__dict__.get('_id', False): return
        self.__dict__['_id'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        registry.insert(self)
        self.x.registerIn(registry)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions:
                s.registerIn(registry)
        self.impl.registerIn(registry)
        self.__dict__['_processing_ex'] = False

    def bind(self, ctx):
        self._ctx = ctx.clone()

    _internals = ['impl']

    def __call__(self, *args, **kwargs):
        return self.impl()

    def reset(self):
        from marketsim import context
        self.impl = self.getImpl()
        ctx_ex = getattr(self, '_ctx_ex', None)
        if ctx_ex: self.impl.bind_ex(ctx_ex)

    def getImpl(self):
        from marketsim.gen._out.strategy.price._oneside import OneSide_strategypriceMarketMakerSideFloat as _strategy_price_OneSide_strategypriceMarketMakerSideFloat
        from marketsim.gen._out.side._sell import Sell_ as _side_Sell_
        from marketsim.gen._out.strategy._combine import Combine_ISingleAssetStrategyISingleAssetStrategy as _strategy_Combine_ISingleAssetStrategyISingleAssetStrategy
        from marketsim.gen._out.side._buy import Buy_ as _side_Buy_
        from marketsim import deref_opt
        return deref_opt(
            _strategy_Combine_ISingleAssetStrategyISingleAssetStrategy(
                deref_opt(
                    _strategy_price_OneSide_strategypriceMarketMakerSideFloat(
                        self.x, deref_opt(_side_Sell_()), 1.0)),
                deref_opt(
                    _strategy_price_OneSide_strategypriceMarketMakerSideFloat(
                        self.x, deref_opt(_side_Buy_()), -1.0))))

    def __getattr__(self, name):
        if name[0:2] != '__' and self.impl:
            return getattr(self.impl, name)
        else:
            raise AttributeError

    @property
    def suspended(self):
        return self.inner.suspended

    def set_suspended(self, value):
        self.inner.suspended = value

    def _send(self, order, source):
        self.on_order_created.fire(order, self)
Esempio n. 23
0
class OneSide_strategypriceMarketMakerIObservableSideFloat(ISingleAssetStrategy):
    """ 
    """ 
    def __init__(self, x = None, side = None, sign = None):
        from marketsim.gen._out.side._observablesell import observableSell_ as _side_observableSell_
        from marketsim.gen._out.event._event import Event
        from marketsim import _
        from marketsim import event
        from marketsim.gen._out.strategy.price._marketmaker import MarketMaker_FloatFloat as _strategy_price_MarketMaker_FloatFloat
        from marketsim import deref_opt
        self.x = x if x is not None else deref_opt(_strategy_price_MarketMaker_FloatFloat())
        self.side = side if side is not None else deref_opt(_side_observableSell_())
        self.sign = sign if sign is not None else 1.0
        self.impl = self.getImpl()
        
        self.on_order_created = Event()
        event.subscribe(self.impl.on_order_created, _(self)._send, self)
    
    @property
    def label(self):
        return repr(self)
    
    _properties = {
        'x' : MarketMaker,
        'side' : IObservableSide,
        'sign' : float
    }
    
    
    
    
    
    
    def __repr__(self):
        return "MarketMakerSide(%(x)s, %(side)s, %(sign)s)" % dict([ (name, getattr(self, name)) for name in self._properties.iterkeys() ])
    
    def bind_ex(self, ctx):
        if self.__dict__.get('_bound_ex', False): return
        self.__dict__['_bound_ex'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        self.__dict__['_ctx_ex'] = ctx.updatedFrom(self)
        self.x.bind_ex(self._ctx_ex)
        self.side.bind_ex(self._ctx_ex)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions: s.bind_ex(self.__dict__['_ctx_ex'])
        self.impl.bind_ex(self.__dict__['_ctx_ex'])
        self.__dict__['_processing_ex'] = False
    
    def reset_ex(self, generation):
        if self.__dict__.get('_reset_generation_ex', -1) == generation: return
        self.__dict__['_reset_generation_ex'] = generation
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        
        self.x.reset_ex(generation)
        self.side.reset_ex(generation)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions: s.reset_ex(generation)
        self.impl.reset_ex(generation)
        self.__dict__['_processing_ex'] = False
    
    def typecheck(self):
        from marketsim import rtti
        from marketsim.gen._out.strategy.price._marketmaker import MarketMaker
        from marketsim.gen._out._side import Side
        from marketsim.gen._out._iobservable._iobservableside import IObservableSide
        rtti.typecheck(MarketMaker, self.x)
        rtti.typecheck(IObservableSide, self.side)
        rtti.typecheck(float, self.sign)
    
    def registerIn(self, registry):
        if self.__dict__.get('_id', False): return
        self.__dict__['_id'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        registry.insert(self)
        self.x.registerIn(registry)
        self.side.registerIn(registry)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions: s.registerIn(registry)
        self.impl.registerIn(registry)
        self.__dict__['_processing_ex'] = False
    
    def bind(self, ctx):
        self._ctx = ctx.clone()
    
    _internals = ['impl']
    def __call__(self, *args, **kwargs):
        return self.impl()
    
    def reset(self):
        from marketsim import context
        self.impl = self.getImpl()
        ctx_ex = getattr(self, '_ctx_ex', None)
        if ctx_ex: self.impl.bind_ex(ctx_ex)
        
    
    def getImpl(self):
        from marketsim.gen._out.math._atan import Atan_Float as _math_Atan_Float
        from marketsim.gen._out.orderbook._queue import Queue_IOrderBookSide as _orderbook_Queue_IOrderBookSide
        from marketsim.gen._out.strategy._generic import Generic_IObservableIOrderIEvent as _strategy_Generic_IObservableIOrderIEvent
        from marketsim.gen._out.observable._breaksatchanges import BreaksAtChanges_IObservableFloat as _observable_BreaksAtChanges_IObservableFloat
        from marketsim.gen._out._constant import constant_Int as _constant_Int
        from marketsim.gen._out.trader._position import Position_IAccount as _trader_Position_IAccount
        from marketsim.gen._out.strategy.price._delta import Delta_strategypriceMarketMaker as _strategy_price_Delta_strategypriceMarketMaker
        from marketsim.gen._out.ops._div import Div_FloatFloat as _ops_Div_FloatFloat
        from marketsim.gen._out.math._exp import Exp_Float as _math_Exp_Float
        from marketsim.gen._out.strategy.price._volume import Volume_strategypriceMarketMaker as _strategy_price_Volume_strategypriceMarketMaker
        from marketsim.gen._out.orderbook._safesideprice import SafeSidePrice_IOrderQueueFloat as _orderbook_SafeSidePrice_IOrderQueueFloat
        from marketsim.gen._out.observable._oneverydt import OnEveryDt_FloatFloat as _observable_OnEveryDt_FloatFloat
        from marketsim.gen._out._constant import constant_Float as _constant_Float
        from marketsim.gen._out.order._floatingprice import FloatingPrice_FloatIObservableIOrderIObservableFloat as _order_FloatingPrice_FloatIObservableIOrderIObservableFloat
        from marketsim.gen._out.ops._div import Div_IObservableFloatFloat as _ops_Div_IObservableFloatFloat
        from marketsim.gen._out.order._curried._price_limit import price_Limit_SideFloat as _order__curried_price_Limit_SideFloat
        from marketsim.gen._out.order._iceberg import Iceberg_IObservableIOrderFloat as _order_Iceberg_IObservableIOrderFloat
        from marketsim.gen._out.event._after import After_Float as _event_After_Float
        from marketsim import deref_opt
        from marketsim.gen._out.orderbook._oftrader import OfTrader_IAccount as _orderbook_OfTrader_IAccount
        return deref_opt(_strategy_Generic_IObservableIOrderIEvent(deref_opt(_order_Iceberg_IObservableIOrderFloat(deref_opt(_order_FloatingPrice_FloatIObservableIOrderIObservableFloat(deref_opt(_order__curried_price_Limit_SideFloat(self.side,deref_opt(_constant_Float((deref_opt(_strategy_price_Volume_strategypriceMarketMaker(self.x))*1000))))),deref_opt(_observable_BreaksAtChanges_IObservableFloat(deref_opt(_observable_OnEveryDt_FloatFloat(deref_opt(_ops_Div_IObservableFloatFloat(deref_opt(_orderbook_SafeSidePrice_IOrderQueueFloat(deref_opt(_orderbook_Queue_IOrderBookSide(deref_opt(_orderbook_OfTrader_IAccount()),self.side)),deref_opt(_constant_Float((100+(deref_opt(_strategy_price_Delta_strategypriceMarketMaker(self.x))*self.sign)))))),deref_opt(_math_Exp_Float(deref_opt(_ops_Div_FloatFloat(deref_opt(_math_Atan_Float(deref_opt(_trader_Position_IAccount()))),deref_opt(_constant_Int(1000)))))))),0.9)))))),deref_opt(_constant_Float(deref_opt(_strategy_price_Volume_strategypriceMarketMaker(self.x)))))),deref_opt(_event_After_Float(deref_opt(_constant_Float(0.0))))))
    
    def __getattr__(self, name):
        if name[0:2] != '__' and self.impl:
            return getattr(self.impl, name)
        else:
            raise AttributeError
    
    @property
    def suspended(self):
        return self.inner.suspended
    
    def set_suspended(self, value):
        self.inner.suspended = value
    
    def _send(self, order, source):
        self.on_order_created.fire(order, self)
Esempio n. 24
0
class Scheduler_Impl(Scheduler_Base):
    """ Keeps a set of events to be launched in the future
    """
    def __init__(self, currentTime=0.0, startTime=None, timeScale='seconds'):
        self._reset(currentTime, startTime)
        self._timeScale = timeScale
        from marketsim.gen._out.event._event import Event
        self.on_clock = Event()

    def __enter__(self):
        global _instance
        _lock.acquire()
        assert _instance == None
        _instance = self
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        global _instance
        assert _instance == self
        _instance = None
        _lock.release()

    def _reset(self, currentTime=0.0, startTime=None):
        """ Resets scheduler to the initial state: empty event set and T=0
        """
        self._elements = []
        self.currentTime = currentTime
        self._startTime = datetime.datetime.now(
        ) if startTime is None else startTime
        self._counter = 0
        self.currentId = None
        self._working = False

    def reset(self):
        self._reset()

    def __repr__(self):
        return "(t=" + str(self.currentTime) + ": " + repr(
            self._elements) + ")"

    @property
    def startTime(self):
        """ DateTime object containing the time of the beginning of the simulation
        """
        return self._startTime

    def timeToOffset(self, abstractTime, timescale='seconds'):
        """ converts an abstract simulation time to a datetime.timedelta object
        """
        return datetime.timedelta(**{timescale: abstractTime})

    @property
    def now(self):
        """ Returns a datetime object containing the "real world" time
        """
        return self._startTime + self.timeToOffset(self.currentTime,
                                                   self._timeScale)

    @property
    def label(self):
        return "scheduler"

    _properties = {'currentTime': float}

    def schedule(self, actionTime, handler):
        """ Schedules an event given by 'handler' to be launched at 'actionTime'.
        Returns a function that can be called in order to cancel the event
        """
        assert actionTime >= self.currentTime
        # in order to keep the right order of events having same action time
        # we differentiate them by incrementing counter
        event = ((actionTime, self._counter), handler)
        self._counter += 1
        heapq.heappush(self._elements, event)

    def scheduleAfter(self, dt, handler):
        """ Schedules an event given by 'handler' to be launched after 'dt' from now
        """
        self.schedule(self.currentTime + dt, handler)

    def async (self, handler):
        self.schedule(self.currentTime, handler)

    def step(self, limitTime):
        if (self._elements <> [] and self._elements[0][0][0] < limitTime):
            ((actionTime, eid), eh) = heapq.heappop(self._elements)
            self.currentId = eid
            self.currentTime = actionTime
            self.on_clock.fire(self)
            #print 't = ', actionTime
            eh()
            return True
        else:
            return False

    def workTill(self, limitTime):
        """ Launches all events with action time in range [currentTime, limitTime)
        in order of their action time and arrival order
        Postcondition: currentTime == limitTime and not exists e: actionTime(e) < limitTime
        """
        if self._working:
            raise Exception("Scheduler is already working")

        t0 = time.clock()
        steps = 0

        self._working = True
        while (self.step(limitTime)):
            steps += 1
        self.currentTime = limitTime
        self._working = False

        dt = time.clock() - t0

        return stat(steps, steps / dt if dt > 0 else -1, dt)

    def advance(self, dt):
        """ Makes the scheduler work 'dt' moments of time more
        """
        self.workTill(self.currentTime + dt)

    def _process_impl(self, intervalFunc, handler):
        handler()
        self.scheduleAfter(intervalFunc(),
                           _(self, intervalFunc, handler)._process_impl)

    def process(self, intervalFunc, handler):
        """ 'intervalFunc' returns intervals of time between consequtive calls to handler
        """
        self.scheduleAfter(intervalFunc(),
                           _(self, intervalFunc, handler)._process_impl)
Esempio n. 25
0
 def __init__(self, currentTime=0.0, startTime=None, timeScale='seconds'):
     self._reset(currentTime, startTime)
     self._timeScale = timeScale
     from marketsim.gen._out.event._event import Event
     self.on_clock = Event()
Esempio n. 26
0
class Strategy_strategypositionRSI_linearFloatIObservableIOrder(ISingleAssetStrategy):
    """ 
    """ 
    def __init__(self, x = None, orderFactory = None):
        from marketsim.gen._out.strategy.position._rsi_linear import RSI_linear_FloatIObservableFloatFloatISingleAssetTrader as _strategy_position_RSI_linear_FloatIObservableFloatFloatISingleAssetTrader
        from marketsim.gen._out.event._event import Event
        from marketsim import _
        from marketsim import event
        from marketsim.gen._out.order._curried._signedvolume_marketsigned import signedVolume_MarketSigned_ as _order__curried_signedVolume_MarketSigned_
        from marketsim import deref_opt
        self.x = x if x is not None else deref_opt(_strategy_position_RSI_linear_FloatIObservableFloatFloatISingleAssetTrader())
        self.orderFactory = orderFactory if orderFactory is not None else deref_opt(_order__curried_signedVolume_MarketSigned_())
        self.impl = self.getImpl()
        
        self.on_order_created = Event()
        event.subscribe(self.impl.on_order_created, _(self)._send, self)
    
    @property
    def label(self):
        return repr(self)
    
    _properties = {
        'x' : RSI_linear,
        'orderFactory' : IFunctionIObservableIOrder_from_IFunctionfloat
    }
    
    
    
    
    def __repr__(self):
        return "RSI_linear(%(x)s, %(orderFactory)s)" % dict([ (name, getattr(self, name)) for name in self._properties.iterkeys() ])
    
    def bind_ex(self, ctx):
        if self.__dict__.get('_bound_ex', False): return
        self.__dict__['_bound_ex'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        self.__dict__['_ctx_ex'] = ctx.updatedFrom(self)
        self.x.bind_ex(self._ctx_ex)
        self.orderFactory.bind_ex(self._ctx_ex)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions: s.bind_ex(self.__dict__['_ctx_ex'])
        self.impl.bind_ex(self.__dict__['_ctx_ex'])
        self.__dict__['_processing_ex'] = False
    
    def reset_ex(self, generation):
        if self.__dict__.get('_reset_generation_ex', -1) == generation: return
        self.__dict__['_reset_generation_ex'] = generation
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        
        self.x.reset_ex(generation)
        self.orderFactory.reset_ex(generation)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions: s.reset_ex(generation)
        self.impl.reset_ex(generation)
        self.__dict__['_processing_ex'] = False
    
    def typecheck(self):
        from marketsim import rtti
        from marketsim.gen._out.strategy.position._rsi_linear import RSI_linear
        from marketsim.gen._out._ifunction._ifunctioniobservableiorder_from_ifunctionfloat import IFunctionIObservableIOrder_from_IFunctionfloat
        rtti.typecheck(RSI_linear, self.x)
        rtti.typecheck(IFunctionIObservableIOrder_from_IFunctionfloat, self.orderFactory)
    
    def registerIn(self, registry):
        if self.__dict__.get('_id', False): return
        self.__dict__['_id'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        registry.insert(self)
        self.x.registerIn(registry)
        self.orderFactory.registerIn(registry)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions: s.registerIn(registry)
        self.impl.registerIn(registry)
        self.__dict__['_processing_ex'] = False
    
    def bind(self, ctx):
        self._ctx = ctx.clone()
    
    _internals = ['impl']
    def __call__(self, *args, **kwargs):
        return self.impl()
    
    def reset(self):
        from marketsim import context
        self.impl = self.getImpl()
        ctx_ex = getattr(self, '_ctx_ex', None)
        if ctx_ex: self.impl.bind_ex(ctx_ex)
        
    
    def getImpl(self):
        from marketsim.gen._out.strategy._generic import Generic_IObservableIOrderIEvent as _strategy_Generic_IObservableIOrderIEvent
        from marketsim.gen._out.strategy.position._position import Position_strategypositionRSI_linear as _strategy_position_Position_strategypositionRSI_linear
        from marketsim import deref_opt
        return deref_opt(_strategy_Generic_IObservableIOrderIEvent(deref_opt(self.orderFactory(deref_opt(_strategy_position_Position_strategypositionRSI_linear(self.x))))))
    
    def __getattr__(self, name):
        if name[0:2] != '__' and self.impl:
            return getattr(self.impl, name)
        else:
            raise AttributeError
    
    @property
    def suspended(self):
        return self.inner.suspended
    
    def set_suspended(self, value):
        self.inner.suspended = value
    
    def _send(self, order, source):
        self.on_order_created.fire(order, self)
Esempio n. 27
0
 def __init__(self):
     Base.__init__(self)
     from marketsim.gen._out.event._event import Event
     self.on_order_created = Event()
Esempio n. 28
0
class Base_Impl(Holder_Impl):
    """ Base class for traders.
    Responsible for bookkeeping P&L of the trader and
    maintaining on_order_sent and on_traded events
    """

    def __init__(self):
        Holder_Impl.__init__(self)
        # event to be fired when an order has been sent
        from marketsim.gen._out.event._event import Event
        self.on_order_sent = Event()
        # event to be fired when an order issued by the trader has been matched
        self.on_order_matched = Event()
        # event to be fired when an order issued by the trader has been cancelled
        self.on_order_disposed = Event()
        # event to be fired when a trader's is traded; to be removed
        self.on_traded = Event()
        self.reset()

    def updateContext(self, context):
        context.trader = self
        context.orderProcessor = self

    def updateContext_ex(self, context):
        context.trader = self
        context.orderProcessor = self

    def reset(self):
        self.PnL = 0

    def _charge(self, price):
        self.PnL -= price

    def onOrderMatched(self, order, price, volume):
        """ Called when a trader's 'order' is traded against 'other' order
        at given 'price' and 'volume'
        Trader's P&L is updated and listeners are notified about the trade
        """
        pv = price * volume
        self.PnL += pv if order.side == Side.Sell else -pv

        self.on_order_matched.fire(self, order, price, volume)
        self.on_traded.fire(self)

    def onOrderDisposed(self, order):
        self.on_order_disposed.fire(self, order)

    def _makeSubscribedTo(self, order):
        """ Makes trader subscribed to 'order' on_matched event
        before sending it to the order book
        Returns the order itself
        """
        order.owner = self
        return order

    def send(self, book, order):
        """ Sends 'order' to 'book'
        After having the order sent notifies listeners about it
        """
        from marketsim.gen._out._iorder import IOrder
        order.bind_ex(self._ctx_ex)
        if isinstance(order, IOrder):
            order = self._makeSubscribedTo(order)
        book.process(order)
        if isinstance(order, IOrder):
            self.on_order_sent.fire(order)
Esempio n. 29
0
class TwoSides_strategypriceMarketMaker(ISingleAssetStrategy):
    """ 
    """ 
    def __init__(self, x = None):
        from marketsim.gen._out.event._event import Event
        from marketsim import _
        from marketsim import event
        from marketsim.gen._out.strategy.price._marketmaker import MarketMaker_FloatFloat as _strategy_price_MarketMaker_FloatFloat
        from marketsim import deref_opt
        self.x = x if x is not None else deref_opt(_strategy_price_MarketMaker_FloatFloat())
        self.impl = self.getImpl()
        
        self.on_order_created = Event()
        event.subscribe(self.impl.on_order_created, _(self)._send, self)
    
    @property
    def label(self):
        return repr(self)
    
    _properties = {
        'x' : MarketMaker
    }
    
    
    def __repr__(self):
        return "MarketMaker(%(x)s)" % dict([ (name, getattr(self, name)) for name in self._properties.iterkeys() ])
    
    def bind_ex(self, ctx):
        if self.__dict__.get('_bound_ex', False): return
        self.__dict__['_bound_ex'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        self.__dict__['_ctx_ex'] = ctx.updatedFrom(self)
        self.x.bind_ex(self._ctx_ex)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions: s.bind_ex(self.__dict__['_ctx_ex'])
        self.impl.bind_ex(self.__dict__['_ctx_ex'])
        self.__dict__['_processing_ex'] = False
    
    def reset_ex(self, generation):
        if self.__dict__.get('_reset_generation_ex', -1) == generation: return
        self.__dict__['_reset_generation_ex'] = generation
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        
        self.x.reset_ex(generation)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions: s.reset_ex(generation)
        self.impl.reset_ex(generation)
        self.__dict__['_processing_ex'] = False
    
    def typecheck(self):
        from marketsim import rtti
        from marketsim.gen._out.strategy.price._marketmaker import MarketMaker
        rtti.typecheck(MarketMaker, self.x)
    
    def registerIn(self, registry):
        if self.__dict__.get('_id', False): return
        self.__dict__['_id'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        registry.insert(self)
        self.x.registerIn(registry)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions: s.registerIn(registry)
        self.impl.registerIn(registry)
        self.__dict__['_processing_ex'] = False
    
    def bind(self, ctx):
        self._ctx = ctx.clone()
    
    _internals = ['impl']
    def __call__(self, *args, **kwargs):
        return self.impl()
    
    def reset(self):
        from marketsim import context
        self.impl = self.getImpl()
        ctx_ex = getattr(self, '_ctx_ex', None)
        if ctx_ex: self.impl.bind_ex(ctx_ex)
        
    
    def getImpl(self):
        from marketsim.gen._out.strategy.price._oneside import OneSide_strategypriceMarketMakerSideFloat as _strategy_price_OneSide_strategypriceMarketMakerSideFloat
        from marketsim.gen._out.side._sell import Sell_ as _side_Sell_
        from marketsim.gen._out.strategy._combine import Combine_ISingleAssetStrategyISingleAssetStrategy as _strategy_Combine_ISingleAssetStrategyISingleAssetStrategy
        from marketsim.gen._out.side._buy import Buy_ as _side_Buy_
        from marketsim import deref_opt
        return deref_opt(_strategy_Combine_ISingleAssetStrategyISingleAssetStrategy(deref_opt(_strategy_price_OneSide_strategypriceMarketMakerSideFloat(self.x,deref_opt(_side_Sell_()),1.0)),deref_opt(_strategy_price_OneSide_strategypriceMarketMakerSideFloat(self.x,deref_opt(_side_Buy_()),-1.0))))
    
    def __getattr__(self, name):
        if name[0:2] != '__' and self.impl:
            return getattr(self.impl, name)
        else:
            raise AttributeError
    
    @property
    def suspended(self):
        return self.inner.suspended
    
    def set_suspended(self, value):
        self.inner.suspended = value
    
    def _send(self, order, source):
        self.on_order_created.fire(order, self)
Esempio n. 30
0
class TradeIfProfitable_ISingleAssetStrategyISingleAssetStrategyIAccountIAccountFloat(
        ISingleAssetStrategy):
    """ **Adaptive strategy that evaluates *inner* strategy efficiency**
    
      and if it is considered as good, sends orders
    
    Parameters are:
    
    **inner**
    	 wrapped strategy 
    
    **account**
    	 defines how strategy trades are booked:
    	 actually traded amount or virtual market orders are
    	 used in order to estimate how the strategy would have traded
    	 if all its orders appeared at market 
    
    **performance**
    	 given a trading account tells
    	 should it be considered as effective or not 
    """
    def __init__(self, inner=None, account=None, performance=None):
        from marketsim.gen._out.strategy.account.inner._inner_virtualmarket import inner_VirtualMarket_ as _strategy_account_inner_inner_VirtualMarket_
        from marketsim.gen._out.event._event import Event
        from marketsim import _
        from marketsim import event
        from marketsim.gen._out.strategy._empty import Empty_ as _strategy_Empty_
        from marketsim.gen._out.strategy.weight.trader._trader_traderefficiencytrend import trader_TraderEfficiencyTrend_Float as _strategy_weight_trader_trader_TraderEfficiencyTrend_Float
        from marketsim import deref_opt
        self.inner = inner if inner is not None else deref_opt(
            _strategy_Empty_())
        self.account = account if account is not None else deref_opt(
            _strategy_account_inner_inner_VirtualMarket_())
        self.performance = performance if performance is not None else deref_opt(
            _strategy_weight_trader_trader_TraderEfficiencyTrend_Float())
        self.impl = self.getImpl()

        self.on_order_created = Event()
        event.subscribe(self.impl.on_order_created, _(self)._send, self)

    @property
    def label(self):
        return repr(self)

    _properties = {
        'inner': ISingleAssetStrategy,
        'account': IFunctionIAccount_from_ISingleAssetStrategy,
        'performance': IFunctionIFunctionfloat_from_IAccount
    }

    def __repr__(self):
        return "TradeIfProfitable(%(inner)s, %(account)s, %(performance)s)" % dict(
            [(name, getattr(self, name))
             for name in self._properties.iterkeys()])

    def bind_ex(self, ctx):
        if self.__dict__.get('_bound_ex', False): return
        self.__dict__['_bound_ex'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        self.__dict__['_ctx_ex'] = ctx.updatedFrom(self)
        self.inner.bind_ex(self._ctx_ex)
        self.account.bind_ex(self._ctx_ex)
        self.performance.bind_ex(self._ctx_ex)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions:
                s.bind_ex(self.__dict__['_ctx_ex'])
        self.impl.bind_ex(self.__dict__['_ctx_ex'])
        self.__dict__['_processing_ex'] = False

    def reset_ex(self, generation):
        if self.__dict__.get('_reset_generation_ex', -1) == generation: return
        self.__dict__['_reset_generation_ex'] = generation
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True

        self.inner.reset_ex(generation)
        self.account.reset_ex(generation)
        self.performance.reset_ex(generation)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions:
                s.reset_ex(generation)
        self.impl.reset_ex(generation)
        self.__dict__['_processing_ex'] = False

    def typecheck(self):
        from marketsim import rtti
        from marketsim.gen._out._isingleassetstrategy import ISingleAssetStrategy
        from marketsim.gen._out._ifunction._ifunctioniaccount_from_isingleassetstrategy import IFunctionIAccount_from_ISingleAssetStrategy
        from marketsim.gen._out._ifunction._ifunctionifunctionfloat_from_iaccount import IFunctionIFunctionfloat_from_IAccount
        rtti.typecheck(ISingleAssetStrategy, self.inner)
        rtti.typecheck(IFunctionIAccount_from_ISingleAssetStrategy,
                       self.account)
        rtti.typecheck(IFunctionIFunctionfloat_from_IAccount, self.performance)

    def registerIn(self, registry):
        if self.__dict__.get('_id', False): return
        self.__dict__['_id'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        registry.insert(self)
        self.inner.registerIn(registry)
        self.account.registerIn(registry)
        self.performance.registerIn(registry)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions:
                s.registerIn(registry)
        self.impl.registerIn(registry)
        self.__dict__['_processing_ex'] = False

    def bind(self, ctx):
        self._ctx = ctx.clone()

    _internals = ['impl']

    def __call__(self, *args, **kwargs):
        return self.impl()

    def reset(self):
        from marketsim import context
        self.impl = self.getImpl()
        ctx_ex = getattr(self, '_ctx_ex', None)
        if ctx_ex: self.impl.bind_ex(ctx_ex)

    def getImpl(self):
        from marketsim.gen._out.strategy._suspendable import Suspendable_ISingleAssetStrategyBoolean as _strategy_Suspendable_ISingleAssetStrategyBoolean
        from marketsim.gen._out.ops._greaterequal import GreaterEqual_FloatFloat as _ops_GreaterEqual_FloatFloat
        from marketsim import deref_opt
        from marketsim.gen._out._constant import constant_Int as _constant_Int
        return deref_opt(
            _strategy_Suspendable_ISingleAssetStrategyBoolean(
                self.inner,
                deref_opt(
                    _ops_GreaterEqual_FloatFloat(
                        deref_opt(
                            self.performance(
                                deref_opt(self.account(self.inner)))),
                        deref_opt(_constant_Int(0))))))

    def __getattr__(self, name):
        if name[0:2] != '__' and self.impl:
            return getattr(self.impl, name)
        else:
            raise AttributeError

    @property
    def suspended(self):
        return self.inner.suspended

    def set_suspended(self, value):
        self.inner.suspended = value

    def _send(self, order, source):
        self.on_order_created.fire(order, self)
Esempio n. 31
0
class Strategy_strategypriceLiquidityProviderIEventSideFloatIObservableIOrder(
        ISingleAssetStrategy):
    """ 
    """
    def __init__(self, x=None, eventGen=None, orderFactory=None):
        from marketsim.gen._out.event._every import Every_Float as _event_Every_Float
        from marketsim.gen._out.math.random._expovariate import expovariate_Float as _math_random_expovariate_Float
        from marketsim.gen._out.event._event import Event
        from marketsim import _
        from marketsim import event
        from marketsim.gen._out.strategy.price._liquidityprovider import LiquidityProvider_FloatFloatIOrderBook as _strategy_price_LiquidityProvider_FloatFloatIOrderBook
        from marketsim.gen._out.order._curried._sideprice_limit import sideprice_Limit_Float as _order__curried_sideprice_Limit_Float
        from marketsim import deref_opt
        self.x = x if x is not None else deref_opt(
            _strategy_price_LiquidityProvider_FloatFloatIOrderBook())
        self.eventGen = eventGen if eventGen is not None else deref_opt(
            _event_Every_Float(deref_opt(_math_random_expovariate_Float(1.0))))
        self.orderFactory = orderFactory if orderFactory is not None else deref_opt(
            _order__curried_sideprice_Limit_Float())
        self.impl = self.getImpl()

        self.on_order_created = Event()
        event.subscribe(self.impl.on_order_created, _(self)._send, self)

    @property
    def label(self):
        return repr(self)

    _properties = {
        'x': LiquidityProvider,
        'eventGen': IEvent,
        'orderFactory':
        IFunctionIObservableIOrder_from_IFunctionSideIFunctionfloat
    }

    def __repr__(self):
        return "LiquidityProvider(%(x)s, %(eventGen)s, %(orderFactory)s)" % dict(
            [(name, getattr(self, name))
             for name in self._properties.iterkeys()])

    def bind_ex(self, ctx):
        if self.__dict__.get('_bound_ex', False): return
        self.__dict__['_bound_ex'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        self.__dict__['_ctx_ex'] = ctx.updatedFrom(self)
        self.x.bind_ex(self._ctx_ex)
        self.eventGen.bind_ex(self._ctx_ex)
        self.orderFactory.bind_ex(self._ctx_ex)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions:
                s.bind_ex(self.__dict__['_ctx_ex'])
        self.impl.bind_ex(self.__dict__['_ctx_ex'])
        self.__dict__['_processing_ex'] = False

    def reset_ex(self, generation):
        if self.__dict__.get('_reset_generation_ex', -1) == generation: return
        self.__dict__['_reset_generation_ex'] = generation
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True

        self.x.reset_ex(generation)
        self.eventGen.reset_ex(generation)
        self.orderFactory.reset_ex(generation)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions:
                s.reset_ex(generation)
        self.impl.reset_ex(generation)
        self.__dict__['_processing_ex'] = False

    def typecheck(self):
        from marketsim import rtti
        from marketsim.gen._out.strategy.price._liquidityprovider import LiquidityProvider
        from marketsim.gen._out._ievent import IEvent
        from marketsim.gen._out._ifunction._ifunctioniobservableiorder_from_ifunctionsideifunctionfloat import IFunctionIObservableIOrder_from_IFunctionSideIFunctionfloat
        rtti.typecheck(LiquidityProvider, self.x)
        rtti.typecheck(IEvent, self.eventGen)
        rtti.typecheck(
            IFunctionIObservableIOrder_from_IFunctionSideIFunctionfloat,
            self.orderFactory)

    def registerIn(self, registry):
        if self.__dict__.get('_id', False): return
        self.__dict__['_id'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        registry.insert(self)
        self.x.registerIn(registry)
        self.eventGen.registerIn(registry)
        self.orderFactory.registerIn(registry)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions:
                s.registerIn(registry)
        self.impl.registerIn(registry)
        self.__dict__['_processing_ex'] = False

    def bind(self, ctx):
        self._ctx = ctx.clone()

    _internals = ['impl']

    def __call__(self, *args, **kwargs):
        return self.impl()

    def reset(self):
        from marketsim import context
        self.impl = self.getImpl()
        ctx_ex = getattr(self, '_ctx_ex', None)
        if ctx_ex: self.impl.bind_ex(ctx_ex)

    def getImpl(self):
        from marketsim.gen._out.side._sell import Sell_ as _side_Sell_
        from marketsim.gen._out.strategy._combine import Combine_ISingleAssetStrategyISingleAssetStrategy as _strategy_Combine_ISingleAssetStrategyISingleAssetStrategy
        from marketsim.gen._out.side._buy import Buy_ as _side_Buy_
        from marketsim.gen._out.strategy.price._onesidestrategy import OneSideStrategy_strategypriceLiquidityProviderIEventSideFloatIObservableIOrderSide as _strategy_price_OneSideStrategy_strategypriceLiquidityProviderIEventSideFloatIObservableIOrderSide
        from marketsim import deref_opt
        return deref_opt(
            _strategy_Combine_ISingleAssetStrategyISingleAssetStrategy(
                deref_opt(
                    _strategy_price_OneSideStrategy_strategypriceLiquidityProviderIEventSideFloatIObservableIOrderSide(
                        self.x, self.eventGen, self.orderFactory,
                        deref_opt(_side_Sell_()))),
                deref_opt(
                    _strategy_price_OneSideStrategy_strategypriceLiquidityProviderIEventSideFloatIObservableIOrderSide(
                        self.x, self.eventGen, self.orderFactory,
                        deref_opt(_side_Buy_())))))

    def __getattr__(self, name):
        if name[0:2] != '__' and self.impl:
            return getattr(self.impl, name)
        else:
            raise AttributeError

    @property
    def suspended(self):
        return self.inner.suspended

    def set_suspended(self, value):
        self.inner.suspended = value

    def _send(self, order, source):
        self.on_order_created.fire(order, self)
Esempio n. 32
0
 def __init__(self):
     Base.__init__(self)
     from marketsim.gen._out.event._event import Event
     self.on_order_created = Event()
Esempio n. 33
0
class Strategy_strategypriceLiquidityProviderIEventSideFloatIObservableIOrder(ISingleAssetStrategy):
    """ 
    """ 
    def __init__(self, x = None, eventGen = None, orderFactory = None):
        from marketsim.gen._out.event._every import Every_Float as _event_Every_Float
        from marketsim.gen._out.math.random._expovariate import expovariate_Float as _math_random_expovariate_Float
        from marketsim.gen._out.event._event import Event
        from marketsim import _
        from marketsim import event
        from marketsim.gen._out.strategy.price._liquidityprovider import LiquidityProvider_FloatFloatIOrderBook as _strategy_price_LiquidityProvider_FloatFloatIOrderBook
        from marketsim.gen._out.order._curried._sideprice_limit import sideprice_Limit_Float as _order__curried_sideprice_Limit_Float
        from marketsim import deref_opt
        self.x = x if x is not None else deref_opt(_strategy_price_LiquidityProvider_FloatFloatIOrderBook())
        self.eventGen = eventGen if eventGen is not None else deref_opt(_event_Every_Float(deref_opt(_math_random_expovariate_Float(1.0))))
        self.orderFactory = orderFactory if orderFactory is not None else deref_opt(_order__curried_sideprice_Limit_Float())
        self.impl = self.getImpl()
        
        self.on_order_created = Event()
        event.subscribe(self.impl.on_order_created, _(self)._send, self)
    
    @property
    def label(self):
        return repr(self)
    
    _properties = {
        'x' : LiquidityProvider,
        'eventGen' : IEvent,
        'orderFactory' : IFunctionIObservableIOrder_from_IFunctionSideIFunctionfloat
    }
    
    
    
    
    
    
    def __repr__(self):
        return "LiquidityProvider(%(x)s, %(eventGen)s, %(orderFactory)s)" % dict([ (name, getattr(self, name)) for name in self._properties.iterkeys() ])
    
    def bind_ex(self, ctx):
        if self.__dict__.get('_bound_ex', False): return
        self.__dict__['_bound_ex'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        self.__dict__['_ctx_ex'] = ctx.updatedFrom(self)
        self.x.bind_ex(self._ctx_ex)
        self.eventGen.bind_ex(self._ctx_ex)
        self.orderFactory.bind_ex(self._ctx_ex)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions: s.bind_ex(self.__dict__['_ctx_ex'])
        self.impl.bind_ex(self.__dict__['_ctx_ex'])
        self.__dict__['_processing_ex'] = False
    
    def reset_ex(self, generation):
        if self.__dict__.get('_reset_generation_ex', -1) == generation: return
        self.__dict__['_reset_generation_ex'] = generation
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        
        self.x.reset_ex(generation)
        self.eventGen.reset_ex(generation)
        self.orderFactory.reset_ex(generation)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions: s.reset_ex(generation)
        self.impl.reset_ex(generation)
        self.__dict__['_processing_ex'] = False
    
    def typecheck(self):
        from marketsim import rtti
        from marketsim.gen._out.strategy.price._liquidityprovider import LiquidityProvider
        from marketsim.gen._out._ievent import IEvent
        from marketsim.gen._out._ifunction._ifunctioniobservableiorder_from_ifunctionsideifunctionfloat import IFunctionIObservableIOrder_from_IFunctionSideIFunctionfloat
        rtti.typecheck(LiquidityProvider, self.x)
        rtti.typecheck(IEvent, self.eventGen)
        rtti.typecheck(IFunctionIObservableIOrder_from_IFunctionSideIFunctionfloat, self.orderFactory)
    
    def registerIn(self, registry):
        if self.__dict__.get('_id', False): return
        self.__dict__['_id'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        registry.insert(self)
        self.x.registerIn(registry)
        self.eventGen.registerIn(registry)
        self.orderFactory.registerIn(registry)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions: s.registerIn(registry)
        self.impl.registerIn(registry)
        self.__dict__['_processing_ex'] = False
    
    def bind(self, ctx):
        self._ctx = ctx.clone()
    
    _internals = ['impl']
    def __call__(self, *args, **kwargs):
        return self.impl()
    
    def reset(self):
        from marketsim import context
        self.impl = self.getImpl()
        ctx_ex = getattr(self, '_ctx_ex', None)
        if ctx_ex: self.impl.bind_ex(ctx_ex)
        
    
    def getImpl(self):
        from marketsim.gen._out.side._sell import Sell_ as _side_Sell_
        from marketsim.gen._out.strategy._combine import Combine_ISingleAssetStrategyISingleAssetStrategy as _strategy_Combine_ISingleAssetStrategyISingleAssetStrategy
        from marketsim.gen._out.side._buy import Buy_ as _side_Buy_
        from marketsim.gen._out.strategy.price._onesidestrategy import OneSideStrategy_strategypriceLiquidityProviderIEventSideFloatIObservableIOrderSide as _strategy_price_OneSideStrategy_strategypriceLiquidityProviderIEventSideFloatIObservableIOrderSide
        from marketsim import deref_opt
        return deref_opt(_strategy_Combine_ISingleAssetStrategyISingleAssetStrategy(deref_opt(_strategy_price_OneSideStrategy_strategypriceLiquidityProviderIEventSideFloatIObservableIOrderSide(self.x,self.eventGen,self.orderFactory,deref_opt(_side_Sell_()))),deref_opt(_strategy_price_OneSideStrategy_strategypriceLiquidityProviderIEventSideFloatIObservableIOrderSide(self.x,self.eventGen,self.orderFactory,deref_opt(_side_Buy_())))))
    
    def __getattr__(self, name):
        if name[0:2] != '__' and self.impl:
            return getattr(self.impl, name)
        else:
            raise AttributeError
    
    @property
    def suspended(self):
        return self.inner.suspended
    
    def set_suspended(self, value):
        self.inner.suspended = value
    
    def _send(self, order, source):
        self.on_order_created.fire(order, self)
Esempio n. 34
0
class OneSide_strategypriceMarketMakerIObservableSideFloat(
        ISingleAssetStrategy):
    """ 
    """
    def __init__(self, x=None, side=None, sign=None):
        from marketsim.gen._out.side._observablesell import observableSell_ as _side_observableSell_
        from marketsim.gen._out.event._event import Event
        from marketsim import _
        from marketsim import event
        from marketsim.gen._out.strategy.price._marketmaker import MarketMaker_FloatFloat as _strategy_price_MarketMaker_FloatFloat
        from marketsim import deref_opt
        self.x = x if x is not None else deref_opt(
            _strategy_price_MarketMaker_FloatFloat())
        self.side = side if side is not None else deref_opt(
            _side_observableSell_())
        self.sign = sign if sign is not None else 1.0
        self.impl = self.getImpl()

        self.on_order_created = Event()
        event.subscribe(self.impl.on_order_created, _(self)._send, self)

    @property
    def label(self):
        return repr(self)

    _properties = {'x': MarketMaker, 'side': IObservableSide, 'sign': float}

    def __repr__(self):
        return "MarketMakerSide(%(x)s, %(side)s, %(sign)s)" % dict(
            [(name, getattr(self, name))
             for name in self._properties.iterkeys()])

    def bind_ex(self, ctx):
        if self.__dict__.get('_bound_ex', False): return
        self.__dict__['_bound_ex'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        self.__dict__['_ctx_ex'] = ctx.updatedFrom(self)
        self.x.bind_ex(self._ctx_ex)
        self.side.bind_ex(self._ctx_ex)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions:
                s.bind_ex(self.__dict__['_ctx_ex'])
        self.impl.bind_ex(self.__dict__['_ctx_ex'])
        self.__dict__['_processing_ex'] = False

    def reset_ex(self, generation):
        if self.__dict__.get('_reset_generation_ex', -1) == generation: return
        self.__dict__['_reset_generation_ex'] = generation
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True

        self.x.reset_ex(generation)
        self.side.reset_ex(generation)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions:
                s.reset_ex(generation)
        self.impl.reset_ex(generation)
        self.__dict__['_processing_ex'] = False

    def typecheck(self):
        from marketsim import rtti
        from marketsim.gen._out.strategy.price._marketmaker import MarketMaker
        from marketsim.gen._out._side import Side
        from marketsim.gen._out._iobservable._iobservableside import IObservableSide
        rtti.typecheck(MarketMaker, self.x)
        rtti.typecheck(IObservableSide, self.side)
        rtti.typecheck(float, self.sign)

    def registerIn(self, registry):
        if self.__dict__.get('_id', False): return
        self.__dict__['_id'] = True
        if self.__dict__.get('_processing_ex', False):
            raise Exception('cycle detected')
        self.__dict__['_processing_ex'] = True
        registry.insert(self)
        self.x.registerIn(registry)
        self.side.registerIn(registry)
        if hasattr(self, '_subscriptions'):
            for s in self._subscriptions:
                s.registerIn(registry)
        self.impl.registerIn(registry)
        self.__dict__['_processing_ex'] = False

    def bind(self, ctx):
        self._ctx = ctx.clone()

    _internals = ['impl']

    def __call__(self, *args, **kwargs):
        return self.impl()

    def reset(self):
        from marketsim import context
        self.impl = self.getImpl()
        ctx_ex = getattr(self, '_ctx_ex', None)
        if ctx_ex: self.impl.bind_ex(ctx_ex)

    def getImpl(self):
        from marketsim.gen._out.math._atan import Atan_Float as _math_Atan_Float
        from marketsim.gen._out.orderbook._queue import Queue_IOrderBookSide as _orderbook_Queue_IOrderBookSide
        from marketsim.gen._out.strategy._generic import Generic_IObservableIOrderIEvent as _strategy_Generic_IObservableIOrderIEvent
        from marketsim.gen._out.observable._breaksatchanges import BreaksAtChanges_IObservableFloat as _observable_BreaksAtChanges_IObservableFloat
        from marketsim.gen._out._constant import constant_Int as _constant_Int
        from marketsim.gen._out.trader._position import Position_IAccount as _trader_Position_IAccount
        from marketsim.gen._out.strategy.price._delta import Delta_strategypriceMarketMaker as _strategy_price_Delta_strategypriceMarketMaker
        from marketsim.gen._out.ops._div import Div_FloatFloat as _ops_Div_FloatFloat
        from marketsim.gen._out.math._exp import Exp_Float as _math_Exp_Float
        from marketsim.gen._out.strategy.price._volume import Volume_strategypriceMarketMaker as _strategy_price_Volume_strategypriceMarketMaker
        from marketsim.gen._out.orderbook._safesideprice import SafeSidePrice_IOrderQueueFloat as _orderbook_SafeSidePrice_IOrderQueueFloat
        from marketsim.gen._out.observable._oneverydt import OnEveryDt_FloatFloat as _observable_OnEveryDt_FloatFloat
        from marketsim.gen._out._constant import constant_Float as _constant_Float
        from marketsim.gen._out.order._floatingprice import FloatingPrice_FloatIObservableIOrderIObservableFloat as _order_FloatingPrice_FloatIObservableIOrderIObservableFloat
        from marketsim.gen._out.ops._div import Div_IObservableFloatFloat as _ops_Div_IObservableFloatFloat
        from marketsim.gen._out.order._curried._price_limit import price_Limit_SideFloat as _order__curried_price_Limit_SideFloat
        from marketsim.gen._out.order._iceberg import Iceberg_IObservableIOrderFloat as _order_Iceberg_IObservableIOrderFloat
        from marketsim.gen._out.event._after import After_Float as _event_After_Float
        from marketsim import deref_opt
        from marketsim.gen._out.orderbook._oftrader import OfTrader_IAccount as _orderbook_OfTrader_IAccount
        return deref_opt(
            _strategy_Generic_IObservableIOrderIEvent(
                deref_opt(
                    _order_Iceberg_IObservableIOrderFloat(
                        deref_opt(
                            _order_FloatingPrice_FloatIObservableIOrderIObservableFloat(
                                deref_opt(
                                    _order__curried_price_Limit_SideFloat(
                                        self.side,
                                        deref_opt(
                                            _constant_Float((deref_opt(
                                                _strategy_price_Volume_strategypriceMarketMaker(
                                                    self.x)) * 1000))))),
                                deref_opt(
                                    _observable_BreaksAtChanges_IObservableFloat(
                                        deref_opt(
                                            _observable_OnEveryDt_FloatFloat(
                                                deref_opt(
                                                    _ops_Div_IObservableFloatFloat(
                                                        deref_opt(
                                                            _orderbook_SafeSidePrice_IOrderQueueFloat(
                                                                deref_opt(
                                                                    _orderbook_Queue_IOrderBookSide(
                                                                        deref_opt(
                                                                            _orderbook_OfTrader_IAccount(
                                                                            )),
                                                                        self.
                                                                        side)),
                                                                deref_opt(
                                                                    _constant_Float((
                                                                        100 +
                                                                        (deref_opt(
                                                                            _strategy_price_Delta_strategypriceMarketMaker(
                                                                                self
                                                                                .x
                                                                            ))
                                                                         * self
                                                                         .sign)
                                                                    ))))),
                                                        deref_opt(
                                                            _math_Exp_Float(
                                                                deref_opt(
                                                                    _ops_Div_FloatFloat(
                                                                        deref_opt(
                                                                            _math_Atan_Float(
                                                                                deref_opt(
                                                                                    _trader_Position_IAccount(
                                                                                    )
                                                                                )
                                                                            )),
                                                                        deref_opt(
                                                                            _constant_Int(
                                                                                1000
                                                                            )))
                                                                ))))),
                                                0.9)))))),
                        deref_opt(
                            _constant_Float(
                                deref_opt(
                                    _strategy_price_Volume_strategypriceMarketMaker(
                                        self.x)))))),
                deref_opt(_event_After_Float(deref_opt(
                    _constant_Float(0.0))))))

    def __getattr__(self, name):
        if name[0:2] != '__' and self.impl:
            return getattr(self.impl, name)
        else:
            raise AttributeError

    @property
    def suspended(self):
        return self.inner.suspended

    def set_suspended(self, value):
        self.inner.suspended = value

    def _send(self, order, source):
        self.on_order_created.fire(order, self)