Strategy vault / Tools & templates
Python Version Spot Cryptocurrency Trading Class Library
Spot cryptocurrency trading library (Python version)
Spot cryptocurrency trading library (Python version)
Parameters
| Name | Default | What it controls |
|---|---|---|
| OpMode | 0 | Order type: market order | pending order |
| MaxSpace | 0.5 | Pending order expiration distance |
| SlidePrice | 0.1 | Order sliding price |
| MaxAmount | 0.8 | Maximum order quantity for opening a position |
| RetryDelay | 500 | Retry delay in milliseconds |
| MAType | 0 | Moving average type: TA.EMA | TA.MA |
| _GetMinStocks | 0.01 | Minimum transaction volume |
Source Python
import types # Import type module
import time # Import time module
import platform # Version information
versionMainValue = None
isFirstCheck = True
def typeOfstr(str):
if str == "list":
if versionMainValue == 2:
return types.ListType
elif versionMainValue == 3:
return list
elif str == "int":
if versionMainValue == 2:
return types.IntType
elif versionMainValue == 3:
return int
elif str == "float":
if versionMainValue == 2:
return types.FloatType
elif versionMainValue == 3:
return float
else:
Log("error , typeOfstr used false")
def CheckVersion():
global versionMainValue,isFirstCheck
platformInfo = platform.python_version()
if platformInfo[0] == '2':
Log("The custodian you are using pythonCompilation environmentpythonversion is",platformInfo)
versionMainValue = 2
elif platformInfo[0] == '3':
Log("The custodian you are using pythonCompilation environmentpythonversion is",platformInfo)
versionMainValue = 3
else:
Log("Other versions")
isFirstCheck = False
def CancelPendingOrders(e, orderType = "") : # Cancel all outstanding pending orders
while True: # Loop
orders = e.GetOrders()
LogStatus("orders:",orders,time.time()) # Test
if(type(orders) != typeOfstr("list")):
Sleep(RetryDelay)
continue
processed = 0
for j in range(len(orders)):
if (type(orderType) == typeOfstr("int") and orders[j].Type != orderType):
continue
e.CancelOrder(orders[j].Id,orders[j])
processed += 1
if (j < (len(orders) - 1)):
Sleep(RetryDelay)
if(processed == 0):
break
def GetAccount(e, waitFrozen = False):
account = null
alreadyAlert = False
while True:
account = _C(e.GetAccount)
if(not waitFrozen or (account.FrozenStocks < _GetMinStocks and account.FrozenBalance < 0.01)):
break
if(not alreadyAlert):
alreadyAlert = True
Log("Found frozen funds or coins in the account",account)
Sleep(RetryDelay)
return account
def StripOrders(e,orderId = null):
order = null
while True:
dropped = 0
orders = _C(e.GetOrders)
for i in range(len(orders)):
if(orders[i].Id == orderId):
order = orders[i]
else:
extra = ""
if(orders[i].DealAmount > 0):
extra = "Transaction:" + str(orders[i].DealAmount)
else:
extra = "unfilled"
e.CancelOrder(orders[i].Id,"Buy Order" if orders[i].Type == ORDER_TYPE_BUY else "Sell Order",extra)
dropped += 1
if(dropped == 0):
break
Sleep(RetryDelay)
return order
def Trade(e,tradeType,tradeAmount,mode,slidePrice,maxAmount,maxSpace,retryDelay):
initAccount = GetAccount(e,True)
nowAccount = initAccount
orderId = null
prePrice = 0.0
dealAmount = 0.0
diffMoney = 0.0
isFirst = True
tradeFunc = e.Buy if tradeType == ORDER_TYPE_BUY else e.Sell
isBuy = (tradeType == ORDER_TYPE_BUY)
while True:
ticker = _C(e.GetTicker)
tradePrice = 0.0
if(isBuy):
tradePrice = _N((ticker.Sell if mode == 0 else ticker.Buy) + slidePrice,4)
else:
tradePrice = _N((ticker.Buy if mode == 0 else ticker.Sell) - slidePrice,4)
if(not orderId):
if(isFirst):
isFirst = False
else:
nowAccount = GetAccount(e,True)
doAmount = 0.0;
if(isBuy):
diffMoney = _N(initAccount.Balance - nowAccount.Balance,4)
dealAmount = _N(nowAccount.Stocks - initAccount.Stocks,4)
doAmount = min(maxAmount,tradeAmount - dealAmount,_N((nowAccount.Balance - 10) / tradePrice,4))
else:
diffMoney = _N(nowAccount.Balance - initAccount.Balance,4)
dealAmount = _N(initAccount.Stocks - nowAccount.Stocks,4)
doAmount = min(maxAmount,tradeAmount - dealAmount,nowAccount.Stocks)
if(doAmount < _GetMinStocks):
break
prePrice = tradePrice
orderId = tradeFunc(tradePrice,doAmount,ticker)
if(not orderId):
CancelPendingOrders(e,tradeType)
else:
if(mode == 0 or (abs(tradePrice - prePrice) > maxSpace)):
orderId = null
order = StripOrders(e,orderId)
if(not order):
orderId = null
Sleep(retryDelay)
if(dealAmount <= 0):
Log("Transaction failed--TradeType:","buy" if tradeType == ORDER_TYPE_BUY else "sell"," ,diffMoney:",diffMoney," ,dealAmount",dealAmount," ,doAmount",doAmount)
return null
ret = {'price': _N(diffMoney/dealAmount,4),'amount':dealAmount}
return ret
# Write like this when calling ret['price'] , ret['amount']
def _Buy(e = exchange,amount = 0):
if isFirstCheck:
CheckVersion()
if (type(e) == typeOfstr("int") or type(e) == typeOfstr("float")):
amount = e
e = exchange
return Trade(e,ORDER_TYPE_BUY,amount,OpMode,SlidePrice,MaxAmount,MaxSpace,RetryDelay)
def _Sell(e = exchange,amount = 0):
if isFirstCheck:
CheckVersion()
if (type(e) == typeOfstr("int") or type(e) == typeOfstr("float")):
amount = e
e = exchange
return Trade(e,ORDER_TYPE_SELL,amount,OpMode,SlidePrice,MaxAmount,MaxSpace,RetryDelay)
def _CancelPendingOrders(e = exchange,orderType = ""):
if isFirstCheck:
CheckVersion()
return CancelPendingOrders(e,orderType)
def _GetAccount(e = exchange):
if isFirstCheck:
CheckVersion()
return _C(e.GetAccount)
_MACalcMethod = [TA.EMA,TA.MA][MAType]
Interval = 200
def Cross(a,b):
if isFirstCheck:
CheckVersion()
crossNum = 0
arr1 = []
arr2 = []
if type(a) == typeOfstr("list") and type(b) == typeOfstr("list"):
arr1 = a
arr2 = b
else:
records = null
while True:
records = exchange.GetRecords()
if records and len(records) > a and len(records) > b:
break
Sleep(Interval)
arr1 = _MACalcMethod(records,a)
arr2 = _MACalcMethod(records,b)
if len(arr1) != len(arr2):
raise Exception("array length not equal")
for i in range(len(arr1) - 1,-1,-1):
if (type(arr1[i]) != typeOfstr("int") and type(arr1[i]) != typeOfstr("float")) or (type(arr2[i]) != typeOfstr("int") and type(arr2[i]) != typeOfstr("float")):
break
if arr1[i] < arr2[i] :
if crossNum > 0 :
break
crossNum -= 1
elif arr1[i] > arr2[i] :
if crossNum < 0 :
break
crossNum += 1
else:
break
return crossNum
# Export Function
ext.Buy = _Buy
ext.Sell = _Sell
ext.CancelPendingOrders = _CancelPendingOrders
ext.GetAccount = _GetAccount
ext.Cross = Cross
# Test
def main():
ret = ext.Buy(0.2)
exchange.Sell(4500,1)
Sleep(10 * 1000)
ext.CancelPendingOrders()
Log("ret:",ret)
avgprice = ret['price']
dealamount = ret['amount']
Log("avgprice:",avgprice," dealamount:",dealamount)Published by 发明者量化-小小梦 on the FMZ strategy square · last modified 2022-03-09. Collected in the Quant Trading Vault. Unvalidated research: re-test with your own data and costs before trusting it.
Build this with AgenKit
A spec is not a trading system. Paste this into your coding agent and AgenKit runs a specialist team — architecture, test-first build, risk gates, review — with paper trading on by default.
/agenkit build a tested, production-ready module from strategies/Python-Version-Spot-Cryptocurrency-Trading-Class-Library.md- npx agenkit install engineering-kit in your project
- Paste the command into your agent and approve each phase
- Get tests, backtest, risk controls and a paper-trading switch
Understand it first
Before you run this, read the lesson behind the idea and how to backtest it honestly. Specs like this one are the survivors of an unknown number of trials; deflate their results accordingly.
Related specs
- Indicator Library Python VersionPython · Tools & templates
- Python APIPython · Tools & templates
- Multi Indicator Configurable Strategy GeneratorPine Script · Tools & templates · 5m
- Trade04 Double Moving Average ATR Channel High and Low PointsMyLanguage · Tools & templates
- C API Call ExampleC++ · Tools & templates
- Digital Currency Futures Multi Variety ATR Strategy TeachingJavaScript · Tools & templates · 1d