Introduction to trading [basic zero tutorial] - Zhihu

Keywords: Blockchain

Let's continue with the following simple policy example to learn how to operate multiple targets in a policy.

def initialize(context):         
               context.security = 'BTC/USDT.binance'         
               context.myaccount = context.get_account('myaccount')

def handle_data(context):         
               current_price = context.get_price(context.security)         
               context.myaccount.buy(context.security, current_price, 0.1) 

Use the list data type to store multiple objects. For example, this is the operation of two objects

def initialize(context):         
    context.security1 = 'BTC/USDT.binance'         
    context.security2 = 'ETH/USDT.binance'         
    context.myaccount = context.get_account('myaccount')  

def handle_data(context):         
    current_price1 = context.get_price(context.security1)         
    context.myaccount.buy(context.security1, current_price1, 0.1)                      
    current_price2 = context.get_price(context.security2)         
    context.myaccount.buy(context.security2, current_price2, 0.1) 

The obvious problem is that when there are many subjects, they have to be written many times, which is very troublesome. Therefore, we need to learn other writing methods. First, we need to learn to store multiple objects with the list data type, as follows:

def initialize(context):         
    context.securities = ['BTC/USDT.binance','ETH/USDT.binance']         
    context.myaccount = context.get_account('myaccount')  

Loop statement

The for loop can traverse items of any sequence, such as a list. The general usage is as follows:

for variable in a sequence:     
    Circulatory body   

In fact, it's very simple. Let's take an example:

for k in ['kelvin','david','cherry','jason']: 
    print(k)  

The post execution log is as follows:

kelvin david cherry jason  

It can be seen that the running process of for statement is to take out the first element 'kelvin' in the list and assign it to K, then execute print(k), i.e. print K in the log, at this time, 'kelvin' in K, then take out the second element 'david' in the list and assign it to K, then execute print(k), i.e. print K in the log, at this time, 'david' in K, and so on, until 'jason' is printed.

Write a simple multi-target strategy

Use the knowledge just learned to change the previous strategy example to a multi-standard version, as follows:

def initialize(context):         
    context.securities = ['BTC/USDT.binance','ETH/USDT.binance']         
    context.myaccount = context.get_account('myaccount')

def handle_data(context):        
    for symbol in context.securities:             
        current_price = context.get_price(symbol)             
        context.myaccount.buy(symbol, current_price, 0.1)


Original link

Vitu.ai - data never panic - blockchain world is no exception

Posted by bla5e on Sun, 03 May 2020 00:09:49 -0700