def main():
    bf = TestBarFeed(bar.Frequency.DAY)
    bars = [
        bar.BasicBar(datetime.datetime(2000, 1, 1), 10, 10, 10, 10, 10, 10, bar.Frequency.DAY),
        bar.BasicBar(datetime.datetime(2000, 1, 2), 10, 10, 10, 10, 10, 10, bar.Frequency.DAY),
        ]
    bf.addBarsFromSequence("orcl", bars)

    logger.getLogger().setLevel(logging.DEBUG)
    strat = BacktestingStrategy(bf, 1)
    strat.run()
Beispiel #2
0
    def __init__(self, cash, barFeed, commission=None):
        super(Broker, self).__init__()

        assert (cash >= 0)
        self.__cash = cash
        if commission is None:
            self.__commission = NoCommission()
        else:
            self.__commission = commission

        #记录当前持仓
        self.__shares = {}

        #新增,记录交易流水,   后期应当改为dataframe格式
        self.__tradeTracker = {}

        #pandas dataframe,记录当前持仓和交易流水
        self.__pdShares = pd.DataFrame({'A': np.random.randn(6)})
        self.__pdTradeTracker = pd.DataFrame({'B': np.random.rand(6)})

        self.__activeOrders = {}
        self.__useAdjustedValues = False
        self.__fillStrategy = fillstrategy.DefaultStrategy()
        self.__logger = logger.getLogger(Broker.LOGGER_NAME)

        # It is VERY important that the broker subscribes to barfeed events before the strategy.
        barFeed.getNewValuesEvent().subscribe(self.onBars)
        self.__barFeed = barFeed
        self.__allowNegativeCash = False
        self.__nextOrderId = 1
    def __init__(self, cash, barFeed, commission=None):
        broker.Broker.__init__(self)

        assert(cash >= 0)
        self.__cash = cash
        if commission is None:
            self.__commission = NoCommission()
        else:
            self.__commission = commission
        self.__shares = {}
        self.__activeOrders = {}
        self.__pairOrders = {}
        self.__useAdjustedValues = False
        self.__fillStrategy = fillstrategy.DefaultStrategy()
        self.__logger = logger.getLogger(Broker.LOGGER_NAME)

        # It is VERY important that the broker subscribes to barfeed events before the strategy.
        barFeed.getNewValuesEvent().subscribe(self.onBars)
        self.__barFeed = barFeed
        self.__allowNegativeCash = False
        self.__nextOrderId = 1

        self.__orderHoldings  = dict()
        self.__maxHoldingDays = None

        self.__strategy = None
Beispiel #4
0
    def __init__(self, cash, barFeed, commission=None, shares={}, activeOrders={}, nextOrderId=1):
        super(PytradeBroker, self).__init__(cash, barFeed, commission)

        self.initializeShares(shares)
        self.initializeActiveOrders(activeOrders, nextOrderId)

        self.setLogger(logger.getLogger(PytradeBroker.LOGGER_NAME))
Beispiel #5
0
    def __init__(self, barFeed, broker):
        assert isinstance(barFeed, pyalgotrade.barfeed.BaseBarFeed
                          ), "barFeed is not a subclass of barfeed.BaseBarFeed"
        assert isinstance(broker, pyalgotrade.broker.Broker
                          ), "broker is not a subclass of broker.Broker"

        self.__barFeed = barFeed
        self.__broker = broker
        self.__activePositions = set()
        self.__orderToPosition = {}
        self.__barsProcessedEvent = observer.Event()
        self.__analyzers = []
        self.__namedAnalyzers = {}
        self.__resampledBarFeeds = []
        self.__dispatcher = dispatcher.Dispatcher()
        self.__broker.getOrderUpdatedEvent().subscribe(self.__onOrderEvent)
        self.__barFeed.getNewValuesEvent().subscribe(self.__onBars)
        self.__resultCurrency = "USD"

        # onStart will be called once all subjects are started.
        self.__dispatcher.getStartEvent().subscribe(self.onStart)
        self.__dispatcher.getIdleEvent().subscribe(self.__onIdle)

        # It is important to dispatch broker events before feed events, specially if we're backtesting.
        self.__dispatcher.addSubject(self.__broker)
        self.__dispatcher.addSubject(self.__barFeed)

        # Initialize logging.
        self.__logger = logger.getLogger(BaseStrategy.LOGGER_NAME)
Beispiel #6
0
    def __init__(self,
                 initialBalances,
                 barFeed,
                 commission=NoCommission(),
                 instrumentTraits=DefaultInstrumentTraits()):
        super(Broker, self).__init__()

        assert isinstance(initialBalances,
                          dict), "initialBalances must be a dictionary"
        assert all([isinstance(symbol, six.string_types) for symbol in initialBalances.keys()]), \
            "Some keys are not strings"
        assert isinstance(barFeed, barfeed.BaseBarFeed
                          ), "barFeed is not a subclass of barfeed.BaseBarFeed"

        self._balances = copy.copy(initialBalances)
        self._barFeed = barFeed
        self._commission = commission
        self._instrumentTraits = instrumentTraits

        self._activeOrders = {}
        self._instrumentPrice = {}
        self._useAdjustedValues = False
        self._fillStrategy = fillstrategy.DefaultStrategy(
            self._instrumentTraits)
        self._logger = logger.getLogger(__name__)

        # It is VERY important that the broker subscribes to barfeed events before the strategy.
        barFeed.getNewValuesEvent().subscribe(self.onBars)
        self._nextOrderId = 1
        self._started = False
Beispiel #7
0
    def __init__(self,
                 instruments,
                 initialCash,
                 fromYear,
                 toYear,
                 debugMode=True,
                 csvStorage="./googlefinance",
                 filterInvalidRows=True):
        self.__logger = logger.getLogger(GoogleFinanceBacktest.LOGGER_NAME)
        self.__finalPortfolioValue = 0

        # Create Feed
        self.__feed = googlefeed.Feed()
        rowFilter = lambda row: row["Close"] == "-" or row["Open"] == "-" or row["High"] == "-" or row["Low"] == "-" or \
                                row["Volume"] == "-"

        self.__feed = googlefinance.build_feed(
            instruments,
            fromYear,
            toYear,
            storage=csvStorage,
            skipErrors=True,
            rowFilter=rowFilter if filterInvalidRows else None)

        # Create Broker
        comissionModel = backtesting.FixedPerTrade(10)
        self.__broker = backtesting.Broker(initialCash,
                                           self.__feed,
                                           commission=comissionModel)
        self.__strategy = TradingSystem(self.__feed,
                                        self.__broker,
                                        debugMode=debugMode)

        # Create Analyzers
        returnsAnalyzer = returns.Returns()
        self.__strategy.attachAnalyzer(returnsAnalyzer)
        dailyResultsAnalyzer = DailyTradingResults()
        self.__strategy.attachAnalyzer(dailyResultsAnalyzer)
        self.__tradesAnalyzer = Trades()
        self.__strategy.attachAnalyzer(self.__tradesAnalyzer)

        # Create plotters
        self.__plotters = []
        self.__plotters.append(
            plotter.StrategyPlotter(self.__strategy,
                                    plotAllInstruments=False,
                                    plotPortfolio=True,
                                    plotBuySell=False))
        self.__plotters[0].getOrCreateSubplot("returns").addDataSeries(
            "Simple returns", returnsAnalyzer.getReturns())
        self.__plotters[0].getOrCreateSubplot("dailyresult").addDataSeries(
            "Daily Results", dailyResultsAnalyzer.getTradeResults())

        for i in range(0, len(instruments)):
            p = plotter.StrategyPlotter(self.__strategy,
                                        plotAllInstruments=False,
                                        plotPortfolio=False)
            p.getInstrumentSubplot(instruments[i])
            self.__plotters.append(p)
    def __init__(self, cash, barFeed, commission=None):
        super(Broker, self).__init__(cash, barFeed)

        if commission is None:
            self.__commission = NoCommission()
        else:
            self.__commission = commission
        self.__instrumentPrice = {}  # Used by setShares
        self.__fillStrategy = fillstrategy.DefaultStrategy()
        self.__logger = logger.getLogger(Broker.LOGGER_NAME)

        # It is VERY important that the broker subscribes to barfeed events before the strategy.
        barFeed.getNewValuesEvent().subscribe(self.onBars)
Beispiel #9
0
    def __init__(self, cash, barFeed):
        super(BaseBrokerImpl, self).__init__()

        assert (cash >= 0)
        self.__cash = cash

        self._shares = {}
        self._activeOrders = {}
        self._allowNegativeCash = False
        self._nextOrderId = 1
        self._barFeed = barFeed
        self.__useAdjustedValues = False
        self.__started = False

        self.__logger = logger.getLogger(BaseBrokerImpl.LOGGER_NAME)
Beispiel #10
0
    def __init__(self, cash, barFeed, commission=None):
        super(Broker, self).__init__()
        assert(cash != None)
        self.__cash = cash
        if commission is None:
            self.__commission = NoCommission()
        else:
            self.__commission = commission
        self.__shares = {}
        self.__activeOrders = {}
        self.__useAdjustedValues = False
        self.__fillStrategy = fillstrategy.DefaultStrategy()
        self.__logger = logger.getLogger(Broker.LOGGER_NAME)

        # It is VERY important that the broker subscribes to barfeed events before the strategy.
        barFeed.getNewValuesEvent().subscribe(self.onBars)
        self.__barFeed = barFeed
        self.__allowNegativeCash = False
        self.__nextOrderId = 1
Beispiel #11
0
    def __init__(self, barFeed, broker):
        self.__barFeed = barFeed
        self.__broker = broker
        self.__activePositions = set()
        self.__orderToPosition = {}
        self.__barsProcessedEvent = observer.Event()
        self.__analyzers = []
        self.__namedAnalyzers = {}
        self.__dispatcher = dispatcher.Dispatcher()
        self.__broker.getOrderUpdatedEvent().subscribe(self.__onOrderEvent)
        self.__barFeed.getNewBarsEvent().subscribe(self.__onBars)

        self.__dispatcher.getStartEvent().subscribe(self.onStart)
        self.__dispatcher.getIdleEvent().subscribe(self.onIdle)

        # It is important to dispatch broker events before feed events, specially if we're backtesting.
        self.__dispatcher.addSubject(self.__broker)
        self.__dispatcher.addSubject(self.__barFeed)

        # Initialize logging.
        self.__logger = logger.getLogger(BaseStrategy.LOGGER_NAME)
Beispiel #12
0
    def __init__(self, cash, tickFeed, commission=None):
        super(Broker, self).__init__()

        assert (cash >= 0)
        self.__cash = cash
        if commission is None:
            self.__commission = NoCommission()
        else:
            self.__commission = commission
        self.__shares = {}
        self.__instrumentPrice = {}  # Used by setShares
        self.__activeOrders = {}
        self.__fillStrategy = fillstrategy.DefaultStrategy()
        self.__logger = logger.getLogger(Broker.LOGGER_NAME)

        # It is VERY important that the broker subscribes to tickfeed events before the strategy.
        tickFeed.getNewValuesEvent().subscribe(self.onTicks)
        self.__tickFeed = tickFeed
        self.__allowNegativeCash = False
        self.__nextOrderId = 1
        self.__started = False
Beispiel #13
0
    def __init__(self, barFeed, broker):
        self.__feed = barFeed
        self.__broker = broker
        self.__activePositions = set()
        self.__orderToPosition = {}
        self.__barsProcessedEvent = observer.Event()
        self.__analyzers = []
        self.__namedAnalyzers = {}
        self.__dispatcher = dispatcher.Dispatcher()
        self.__broker.getOrderUpdatedEvent().subscribe(self.__onOrderEvent)
        self.__feed.getNewBarsEvent().subscribe(self.__onBars)

        self.__dispatcher.getStartEvent().subscribe(self.onStart)
        self.__dispatcher.getIdleEvent().subscribe(self.onIdle)

        # It is important to dispatch broker events before feed events, specially if we're backtesting.
        self.__dispatcher.addSubject(self.__broker)
        self.__dispatcher.addSubject(self.__feed)

        # Initialize logging.
        self.__logger = logger.getLogger(BaseStrategy.LOGGER_NAME)
Beispiel #14
0
    def __init__(self,
                 dbfilepah="/var/pytrade/sqlitedb",
                 googleFinanceDir="/var/pytrade/googlefinance",
                 username=None,
                 tradingAlgorithmGenerator=None,
                 codes=None,
                 date=dt.as_utc(datetime.now()),
                 maxlen=90,
                 debugmode=False):
        if codes is None:
            self.__codes = [
                "ABEV3", "BBAS3", "BBDC3", "BBDC4", "BBSE3", "BRAP4", "BRFS3",
                "BRKM5", "BRML3", "BVMF3", "CCRO3", "CIEL3", "CMIG4", "CPFE3",
                "CPLE6", "CSAN3", "CSNA3", "CTIP3", "CYRE3", "ECOR3", "EGIE3",
                "EMBR3", "ENBR3", "EQTL3", "ESTC3", "FIBR3", "GGBR4", "GOAU4",
                "HYPE3", "ITSA4", "ITUB4", "JBSS3", "KLBN11", "KROT3", "LAME4",
                "LREN3", "MRFG3", "MRVE3", "MULT3", "NATU3", "PCAR4", "PETR3",
                "PETR4", "QUAL3", "RADL3", "RENT3", "RUMO3", "SANB11", "SBSP3",
                "SMLE3", "SUZB5", "TIMP3", "UGPA3", "USIM5", "VALE3", "VALE5",
                "VIVT4", "WEGE3"
            ]
        else:
            self.__codes = codes

        self.__logger = logger.getLogger(PytradeApi.LOGGER_NAME)
        self.__dbFilePath = dbfilepah
        self.__googleFinanceDir = googleFinanceDir
        self.__debugMode = debugmode
        self.__tradingAlgorithmGenerator = tradingAlgorithmGenerator
        self.__currentDate = date
        self.__maxLen = maxlen

        self.initializeDataProvider()
        self.initializeFeed()

        self.__username = username
        if username is not None:
            self.initializeBroker(username)
            self.initializeStrategy(
            )  # tradingAlgorithmGenerator must not be None
Beispiel #15
0
    def __init__(self, barFeed, broker):
        self.__barFeed = barFeed #ok
        self.__broker = broker #ok
        self.__activePositions = set() #用于管理活动的订单,如已经提交的买单
        self.__orderToPosition = {} ###
        self.__barsProcessedEvent = observer.Event() ###
        self.__analyzers = []
        self.__namedAnalyzers = {}
        self.__resampledBarFeeds = [] #
        self.__dispatcher = dispatcher.Dispatcher() #策略的循环触发机制由该dispatch完成
        self.__broker.getOrderUpdatedEvent().subscribe(self.__onOrderEvent) #__onOrderEvent作为策略和broker之前的桥梁;当订单有变化的时候会通知到这里
        self.__barFeed.getNewValuesEvent().subscribe(self.__onBars) #__onBars作为策略和barfeed之间的桥梁,当bar有变化的时候触发此函数

        self.__dispatcher.getStartEvent().subscribe(self.onStart) #全局的dispatch 启动时候需要调用的
        self.__dispatcher.getIdleEvent().subscribe(self.__onIdle)

        # It is important to dispatch broker events before feed events, specially if we're backtesting.
        self.__dispatcher.addSubject(self.__broker) #把broker加入驱动bus
        self.__dispatcher.addSubject(self.__barFeed) #把bar加入驱动bus

        # Initialize logging.
        self.__logger = logger.getLogger(BaseStrategy.LOGGER_NAME)
Beispiel #16
0
 def __init__(self, msg_queue):
     """API对象的初始化函数"""
     super(CTPTdApi, self).__init__()
     
     self.reqID = 0              # 操作请求编号
     self.orderRef = 0           # 订单编号
     
     self.connectionStatus = False       # 连接状态
     self.loginStatus = False            # 登录状态
     
     self.userID = None          # 账号
     self.password = None        # 密码
     self.brokerID = None        # 经纪商代码
     self.address = None         # 服务器地址
     
     self.frontID = None            # 前置机编号
     self.sessionID = None          # 会话编号
     
     self.__msg_queue= msg_queue
     self.__oders = set()
     
     self._logger = getLogger('CTP')
Beispiel #17
0
    def __init__(self, tickFeed, broker):
        self.__tickFeed = tickFeed
        self.__broker = broker
        self.__activePositions = set()
        self.__orderToPosition = {}
        self.__ticksProcessedEvent = observer.Event()
        self.__analyzers = []
        self.__namedAnalyzers = {}
        # self.__resampledTickFeeds = []
        self.__dispatcher = dispatcher.Dispatcher()
        self.__broker.getOrderUpdatedEvent().subscribe(self.__onOrderEvent)
        self.__tickFeed.getNewValuesEvent().subscribe(self.__onTicks)

        # onStart will be called once all subjects are started.
        self.__dispatcher.getStartEvent().subscribe(self.onStart)
        self.__dispatcher.getIdleEvent().subscribe(self.__onIdle)

        # It is important to dispatch broker events before feed events, specially if we're backtesting.
        self.__dispatcher.addSubject(self.__broker)
        self.__dispatcher.addSubject(self.__tickFeed)

        # Initialize logging.
        self.__logger = logger.getLogger(BaseTickStrategy.LOGGER_NAME)
Beispiel #18
0
    def __init__(self, instruments, initialCash, year, debugMode=True, csvStorage="./googlefinance"):
        self.__logger = logger.getLogger(GoogleFinanceBacktest.LOGGER_NAME)
        self.__finalPortfolioValue = 0

        # Create Feed
        self.__feed = googlefeed.Feed()
        rowFilter = lambda row: row["Close"] == "-" or row["Open"] == "-" or row["High"] == "-" or row["Low"] == "-" or \
                                row["Volume"] == "-"

        self.__feed = googlefinance.build_feed(instruments, year, year, storage=csvStorage, skipErrors=True, rowFilter=rowFilter)

        # Create Broker
        comissionModel = backtesting.FixedPerTrade(10)
        self.__broker = backtesting.Broker(initialCash, self.__feed, commission=comissionModel)
        self.__strategy = TradingSystem(self.__feed, self.__broker, debugMode=debugMode)

        # Create Analyzers
        returnsAnalyzer = returns.Returns()
        self.__strategy.attachAnalyzer(returnsAnalyzer)
        dailyResultsAnalyzer = DailyTradingResults()
        self.__strategy.attachAnalyzer(dailyResultsAnalyzer)

        # Create plotters
        self.__plotters = []
        self.__plotters.append(
            plotter.StrategyPlotter(self.__strategy, plotAllInstruments=False, plotPortfolio=True, plotBuySell=False))
        self.__plotters[0].getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())
        self.__plotters[0].getOrCreateSubplot("dailyresult").addDataSeries("Daily Results", dailyResultsAnalyzer.getTradeResults())

        for i in range(0, len(instruments), 3):
            p = plotter.StrategyPlotter(self.__strategy, plotAllInstruments=False, plotPortfolio=False)
            p.getInstrumentSubplot(instruments[i])
            self.__plotters.append(p)
            if i < len(instruments) - 1:
                p.getInstrumentSubplot(instruments[i + 1])
            if i < len(instruments) - 2:
                p.getInstrumentSubplot(instruments[i + 2])
Beispiel #19
0
import time
import datetime
import threading
import Queue

from pyalgotrade import bar
from pyalgotrade import barfeed
from pyalgotrade import dataseries
from pyalgotrade import logger
from pyalgotrade.utils import dt
from pyalgotrade import observer

import api

logger = logger.getLogger("bitfinex")


def utcnow():
    return dt.as_utc(datetime.datetime.utcnow())


class TradeBar(bar.Bar):
    __slots__ = ('__dateTime', '__tradeId', '__price', '__amount', '__type')

    last_datetime = None

    def __init__(self, bardict):
        trade_dt = datetime.datetime.fromtimestamp(bardict['timestamp'])
        if TradeBar.last_datetime is not None:
            if trade_dt <= TradeBar.last_datetime:
Beispiel #20
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from exchange.bitmex.liveApi import liveLogger
import pyalgotrade.logger as log
# logger = liveLogger.getLiveLogger("Exception")
logger = log.getLogger("Exception")


def ErrorShow(msg):
    logger.warning(msg)
import Queue
import datetime
import threading
import time

from pyalgotrade import bar
from pyalgotrade import barfeed
from pyalgotrade import dataseries
from pyalgotrade import logger
from pyalgotrade import observer
from pyalgotrade.utils import dt

import api

logger = logger.getLogger("mercadobitcoin")


def utcnow():
    return dt.as_utc(datetime.datetime.utcnow())


class TradeBar(bar.Bar):
    __slots__ = ('__dateTime', '__tradeId', '__price', '__amount', '__type')

    last_datetime = None

    def __init__(self, bardict):
        trade_dt = datetime.datetime.fromtimestamp(bardict['date'])
        if TradeBar.last_datetime is not None:
            if trade_dt <= TradeBar.last_datetime:
import time
import datetime
import threading
import Queue

from pyalgotrade import bar
from pyalgotrade import barfeed
from pyalgotrade import dataseries
from pyalgotrade import logger
from pyalgotrade.utils import dt
from pyalgotrade import observer

import api


logger = logger.getLogger("bitfinex")


def utcnow():
    return dt.as_utc(datetime.datetime.utcnow())


class TradeBar(bar.Bar):
    __slots__ = ('__dateTime', '__tradeId', '__price', '__amount', '__type')

    last_datetime = None

    def __init__(self, bardict):
        trade_dt = datetime.datetime.fromtimestamp(bardict['timestamp'])
        if TradeBar.last_datetime is not None:
            if trade_dt <= TradeBar.last_datetime:
Beispiel #23
0
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
.. moduleauthor:: Gabriel Martin Becedillas Ruiz <*****@*****.**>
"""

from exchange.bitmex.bitmex_sdk import ApiClient
from exchange.bitmex.bitmex_client import BitmexTradeClient
# from exchange.bitmex.liveApi import liveLogger
import pyalgotrade.logger as log
from exchange.bitmex.liveApi.liveUtils import *

# logger = liveLogger.getLiveLogger("K-Line")
logger = log.getLogger("K-line")
# client = ApiClient('API_KEY', 'API_SECRET')


def getKLineBar(identifier, precision, period, length=1):
    logger.info('getKLine:%s %s %s %s' %
                (identifier, precision, period, length))
    # length = length + 1 if length < 10 else 10
    length = 100
    logger.info("===========kline start: {}===============".format(
        identifier.getSymbol()))
    client = BitmexTradeClient(identifier)

    # klines = client.mget('/market/history/kline', symbol=identifier.getSymbol(), period='%dmin' % period, size=length)
    klines = client.get_kline(identifier.getSymbol(), **{
        'binSize': precision,
Beispiel #24
0
Created on Sun Dec 11 14:31:04 2016
"""

import time
import Queue
import pymongo
from datetime import datetime

from pyalgotrade import broker
from pyalgotrade.logger import getLogger
from pyalgotrade.cn.utl import getMongoInfo
from api import CTPTdApi


logger = getLogger('CTP_broker')

class FutureTraits(broker.InstrumentTraits):
    def roundQuantity(self, quantity):
        return round(quantity, 2)
        
    def getCommission(self, instrument_id):
        return 0
        

class LiveBroker(broker.Broker):
    """A CTP live broker.

    .. note::
        * Only limit orders are supported.
        * Orders are automatically set as **goodTillCanceled=True** and  **allOrNone=False**.
 def __init__(self, maxLen=None):
     self.__logger = logger.getLogger(DailyTradingResults.LOGGER_NAME)
     self.__totalCapital = dataseries.SequenceDataSeries(maxLen=maxLen)
     self.__tradeResults = dataseries.SequenceDataSeries(maxLen=maxLen)
     self.__posTracker = {}
     self.__dailyTradeValues = {}
Beispiel #26
0
from pi.mysql import client
from pi.ibHelper.barfeed import RealTimeBar
from datetime import datetime, timedelta
from MdApi.MdApi import *
from pi import CONSTANTS
from pyalgotrade import logger
import sys

logger = logger.getLogger("ctpClient")

class Quote(CThostFtdcMdSpi):
    def __init__(self, mdapi, broker_id, user_id, password):
        CThostFtdcMdSpi.__init__(self)
        self.__reqNum = 0
        self.__contactIDs = []
        self.__insertIntoMysql = False
        self.__dumpToFile = True
        self.__md = mdapi
        self.__broker_id = broker_id
        self.__user_id = user_id
        self.__password = password
        self.__mysqlCon = None
        self.__starttime = datetime.now()
        self.__file = None

    def isDumpToMysql(self, dump=True):
        self.__insertIntoMysql = dump

    def isDumpToFile(self, dump=True):
        self.__dumpToFile = dump
Beispiel #27
0
import threading
import time
import queue

from pyalgotrade import bar
from pyalgotrade import barfeed
from pyalgotrade import dataseries
from pyalgotrade import resamplebase
from pyalgotrade.utils import dt

import exchange.bitmex.liveApi.commonApi as api
# from exchange.bitmex.liveApi import liveLogger
from exchange.bitmex.liveApi import liveUtils
import pyalgotrade.logger as log
# logger = liveLogger.getLiveLogger("Barfeed")
logger = log.getLogger("Barfeed")


class liveBar(bar.BasicBar):
    def __init__(self, barDict, frequency):
        self.__DateTimeLocal = liveUtils.timestamp_to_DateTimeLocal(
            barDict["Timestamp"])
        super(liveBar,
              self).__init__(dt.timestamp_to_datetime(barDict["Timestamp"]),
                             barDict["Open"], barDict["High"], barDict["Low"],
                             barDict["Close"], barDict["Volume"], None,
                             frequency)

    def getDateTimeLocal(self):
        return self.__DateTimeLocal
Beispiel #28
0
from exchange.bitmex.liveApi.TradeClientBase import *
from exchange.bitmex.liveApi.liveUtils import *
from pyalgotrade.utils import dt
# from exchange.bitmex.liveApi import liveLogger
import pyalgotrade.logger as log
from exchange.bitmex.bitmex_sdk import ApiClient, ApiError
from exchange.bitmex.bitmex import Bitmex
from exchange.bitmex.api_keys import API_KEY
from exchange.bitmex.api_keys import API_SECRET

# https://github.com/huobiapi/API_Docs/wiki
# https://github.com/huobiapi/API_Docs/wiki/REST_api_reference
# logger = liveLogger.getLiveLogger("bitmex_client")
logger = log.getLogger("bitmex_client")


def Str2float(func):
    def waper(*args, **kwargs):
        return float(func(*args, **kwargs))

    return waper


class BitmexOrderType(object):
    BuyLimit = 'buy-limit'  # 限价买
    BuyMarket = 'buy-market'  # 市价买
    SellLimit = 'sell-limit'  # 限价卖
    SellMarket = 'sell-market'  # 市价卖


class BitmexOrderState(object):
Beispiel #29
0
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
.. moduleauthor:: Gabriel Martin Becedillas Ruiz <*****@*****.**>
"""

import os
import signal

from pyalgotrade import dispatchprio
from pyalgotrade import logger as logging
from pyalgotrade import observer, utils

logger = logging.getLogger(__name__)


# This class is responsible for dispatching events from multiple subjects, synchronizing them if necessary.
class Dispatcher(object):
    def __init__(self):
        self.__subjects = []
        self.__stop = False
        self.__startEvent = observer.Event()
        self.__idleEvent = observer.Event()
        self.__currDateTime = None

    # Returns the current event datetime. It may be None for events from realtime subjects.
    def getCurrentDateTime(self):
        return self.__currDateTime
Beispiel #30
0
 def onBars(self, bars):
     self.info("bla")
     logger.getLogger("custom").info("ble")
Beispiel #31
0
# -*- coding: utf-8 -*-

import Queue

#must at top
from  pyalgotrade import logger
logger.log_format  = '%(asctime)s [%(filename)s:%(lineno)d:%(funcName)s]%(levelname)s %(message)s'
logging = logger.getLogger()

from pyalgotrade import strategy
from pyalgotrade.technical import ma
from pyalgotrade.technical import cross
from pyalgotrade import bar 


import vic.exchange.vic_coinigy.wsclient 
import vic.exchange.vic_coinigy.httpclient 

import vic.exchange.livepyalgo.broker as broker
import vic.exchange.livepyalgo.livebroker as livebroker
import vic.exchange.livepyalgo.livefeed as livefeed

from lib.mysql_pool import MysqlPool


import pdb

channels_conf = "../conf/market-channels.txt"
mysql = MysqlPool('127.0.0.1', 3308, 'ops', 'ops!@#9988', 'vic_ticker', 'utf8')

def readChannels(path):
Beispiel #32
0
@author: tliu
'''
import MySQLdb
import csv
from pi.ibHelper.barfeed import RealTimeBar
from optparse import OptionParser
from pi import CONSTANTS
from datetime import datetime, timedelta
from pyalgotrade import bar
from csv import DictReader
from pyalgotrade import logger
import traceback


logger = logger.getLogger("mysqlconnection")

class mysqlConnection:
    def __init__(self, 
                 host=CONSTANTS.HOST, 
                 username=CONSTANTS.USERNAME, 
                 password=CONSTANTS.PASSWORD, 
                 database=CONSTANTS.DATABASE):
        self.__con = MySQLdb.Connect(host, username, password, database)

    def getConnection(self):
        return self.__con

    def __addBar(self, symbol, bar, cursor):
        string = ("INSERT INTO data (`symbol`, `date`,`milliseconds`, `open`, `close`, `high`, `low`, `volume`) " + 
                  "VALUES ('{0:s}', '{1:%Y-%m-%d %H:%M:%S}', '{4:d}','{2:f}', '{2:f}', '{2:f}', '{2:f}', '{3:f}')")
Beispiel #33
0
 def __init__(self, frequency, maxLen=dataseries.DEFAULT_MAX_LEN):
     membf.BarFeed.__init__(self, frequency, maxLen)
     self.__barFilter = None
     self.__dailyTime = datetime.time(0, 0, 0)
     self.__logger = logger.getLogger(BarFeed.LOGGER_NAME)
Beispiel #34
0
.. moduleauthor:: Gabriel Martin Becedillas Ruiz <*****@*****.**>
"""
import queue
import threading
import time

# from exchange.bitmex.liveApi import liveLogger
import pyalgotrade.logger as log
from pyalgotrade import broker
# from exchange.bitmex.liveApi import broker
from pyalgotrade.bitstamp import common

from exchange.bitmex.liveApi import liveUtils

# logger = liveLogger.getLiveLogger("Broker")
logger = log.getLogger("Broker")


class BTCTraits(broker.InstrumentTraits):
    def roundQuantity(self, quantity):
        return round(quantity, 4)


common.BTCTraits = BTCTraits


def build_order_from_open_order(openOrder, instrumentTraits):
    if openOrder.isBuy():
        action = broker.Order.Action.BUY
    elif openOrder.isSell():
        action = broker.Order.Action.SELL
Beispiel #35
0
 def getLogger(self):
     if self.__logger == None:
         self.__logger = logger.getLogger(ForexBacktestingStrategy.LOGGER_NAME)        
     return self.__logger
Beispiel #36
0
from pyalgotrade import broker
from pyalgotrade.bar import Frequency
from pyalgotrade.technical import ma
from pyalgotrade.technical import cross
# from pyalgotrade import plotter
from pyalgotrade.stratanalyzer import returns
from exchange.bitmex.liveApi.livebarfeed import LiveFeed
from exchange.bitmex.liveApi.livebroker import LiveBroker

from exchange.bitmex.bitmex_client import BitmexTradeClient as BitmexClient
from exchange.bitmex.bitmex_client import BitmexCoinType
# from exchange.bitmex.liveApi import liveLogger
from pyalgotrade import logger as log

# logger = liveLogger.getLiveLogger("MyStrategy")
logger = log.getLogger("MyStrategy")

COIN_TYPE = BitmexCoinType('btc', 'usdt')
K_PERIOD = 60
REQ_DELAY = 0


class MyStrategy(strategy.BaseStrategy):
    def __init__(self, feed, instrument, brk):
        super(MyStrategy, self).__init__(feed, brk)
        self.__position = None
        self.__instrument = instrument
        # We'll use adjusted close values instead of regular close values.
        self.__prices = feed[instrument].getPriceDataSeries()
        self.__sma = {}
        self.__sma[60] = ma.SMA(self.__prices, 60)
Beispiel #37
0
def getLiveLogger(name):
    log = logger.getLogger(name)
    initLogger(log)
    return log
Beispiel #38
0
    def __init__(self, feed, cash=None, orders=None, shares=None):
        super(PytradeBroker, self).__init__(cash, feed)

        self.initializeActiveOrders(orders)
        self.initializeShares(shares)
        self.setLogger(logger.getLogger(PytradeBroker.LOGGER_NAME))
Beispiel #39
0
 def onBars(self, bars):
     self.info("bla")
     logger.getLogger("custom").info("ble")
Beispiel #40
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2018/11/23 13:57    @Author  : xycfree
# @Descript: 
from coinmarketcap import Market
from pyalgotrade import logger as log

logger = log.getLogger("common")
def base_usdt_price(coin=''):
    """   Valid cryptocurrency values are: "BTC", "ETH" "XRP", "LTC", and "BCH"
        id:  1 BTC    2 LTC    1321 ETH    52:XRP  1831  BCH
    """
    if not coin:
        _id = '1'
    elif coin.upper() == 'BTC':
        _id = "1"
    elif coin.upper() == "LTC":
        _id = "2"
    elif coin.upper() == 'ETH':
        _id = "1321"
    elif coin.upper() == 'XRP':
        _id = "52"
    elif coin.upper() == 'BCH':
        _id = '1831'
    else:
        _id = ""
    if _id:
        data = Market().ticker(currency=_id).get('data', {})
        logger.info("data: {}".format(data))
        if not data:
            return 0