code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
from mpi4py import MPI
import tensorflow as tf, ppo.baselines.common.tf_util as U, numpy as np
class RunningMeanStd(object):
# https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm
def __init__(self, epsilon=1e-2, shape=(), comm=None):
self.comm = MPI.COMM_WORLD if comm is None else comm
self._sum = tf.get_variable(
dtype=tf.float64,
shape=shape,
initializer=tf.constant_initializer(0.0),
name="runningsum", trainable=False)
self._sumsq = tf.get_variable(
dtype=tf.float64,
shape=shape,
initializer=tf.constant_initializer(epsilon),
name="runningsumsq", trainable=False)
self._count = tf.get_variable(
dtype=tf.float64,
shape=(),
initializer=tf.constant_initializer(epsilon),
name="count", trainable=False)
self.shape = shape
self.mean = tf.to_float(self._sum / self._count)
self.std = tf.sqrt( tf.maximum( tf.to_float(self._sumsq / self._count) - tf.square(self.mean) , 1e-2 ))
newsum = tf.placeholder(shape=self.shape, dtype=tf.float64, name='sum')
newsumsq = tf.placeholder(shape=self.shape, dtype=tf.float64, name='var')
newcount = tf.placeholder(shape=[], dtype=tf.float64, name='count')
self.incfiltparams = U.function([newsum, newsumsq, newcount], [],
updates=[tf.assign_add(self._sum, newsum),
tf.assign_add(self._sumsq, newsumsq),
tf.assign_add(self._count, newcount)])
def update(self, x):
x = x.astype('float64')
n = int(np.prod(self.shape))
totalvec = np.zeros(n*2+1, 'float64')
addvec = np.concatenate([x.sum(axis=0).ravel(), np.square(x).sum(axis=0).ravel(), np.array([len(x)],dtype='float64')])
self.comm.Allreduce(addvec, totalvec, op=MPI.SUM)
self.incfiltparams(totalvec[0:n].reshape(self.shape), totalvec[n:2*n].reshape(self.shape), totalvec[2*n])
@U.in_session
def test_runningmeanstd():
for (x1, x2, x3) in [
(np.random.randn(3), np.random.randn(4), np.random.randn(5)),
(np.random.randn(3,2), np.random.randn(4,2), np.random.randn(5,2)),
]:
rms = RunningMeanStd(epsilon=0.0, shape=x1.shape[1:])
U.initialize()
x = np.concatenate([x1, x2, x3], axis=0)
ms1 = [x.mean(axis=0), x.std(axis=0)]
rms.update(x1)
rms.update(x2)
rms.update(x3)
ms2 = [rms.mean.eval(), rms.std.eval()]
assert np.allclose(ms1, ms2)
@U.in_session
def test_dist():
np.random.seed(0)
p1,p2,p3=(np.random.randn(3,1), np.random.randn(4,1), np.random.randn(5,1))
q1,q2,q3=(np.random.randn(6,1), np.random.randn(7,1), np.random.randn(8,1))
# p1,p2,p3=(np.random.randn(3), np.random.randn(4), np.random.randn(5))
# q1,q2,q3=(np.random.randn(6), np.random.randn(7), np.random.randn(8))
comm = MPI.COMM_WORLD
assert comm.Get_size()==2
if comm.Get_rank()==0:
x1,x2,x3 = p1,p2,p3
elif comm.Get_rank()==1:
x1,x2,x3 = q1,q2,q3
else:
assert False
rms = RunningMeanStd(epsilon=0.0, shape=(1,))
U.initialize()
rms.update(x1)
rms.update(x2)
rms.update(x3)
bigvec = np.concatenate([p1,p2,p3,q1,q2,q3])
def checkallclose(x,y):
print(x,y)
return np.allclose(x,y)
assert checkallclose(
bigvec.mean(axis=0),
rms.mean.eval(),
)
assert checkallclose(
bigvec.std(axis=0),
rms.std.eval(),
)
if __name__ == "__main__":
# Run with mpirun -np 2 python <filename>
test_dist() | ytopt | /ytopt-0.0.1.tar.gz/ytopt-0.0.1/ppo/baselines/common/mpi_running_mean_std.py | mpi_running_mean_std.py |
import tensorflow as tf
import numpy as np
from ppo.baselines.common.tf_util import get_session
class RunningMeanStd(object):
# https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm
def __init__(self, epsilon=1e-4, shape=()):
self.mean = np.zeros(shape, 'float64')
self.var = np.ones(shape, 'float64')
self.count = epsilon
def update(self, x):
batch_mean = np.mean(x, axis=0)
batch_var = np.var(x, axis=0)
batch_count = x.shape[0]
self.update_from_moments(batch_mean, batch_var, batch_count)
def update_from_moments(self, batch_mean, batch_var, batch_count):
self.mean, self.var, self.count = update_mean_var_count_from_moments(
self.mean, self.var, self.count, batch_mean, batch_var, batch_count)
def update_mean_var_count_from_moments(mean, var, count, batch_mean, batch_var, batch_count):
delta = batch_mean - mean
tot_count = count + batch_count
new_mean = mean + delta * batch_count / tot_count
m_a = var * count
m_b = batch_var * batch_count
M2 = m_a + m_b + np.square(delta) * count * batch_count / tot_count
new_var = M2 / tot_count
new_count = tot_count
return new_mean, new_var, new_count
class TfRunningMeanStd(object):
# https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm
'''
TensorFlow variables-based implmentation of computing running mean and std
Benefit of this implementation is that it can be saved / loaded together with the tensorflow model
'''
def __init__(self, epsilon=1e-4, shape=(), scope=''):
sess = get_session()
self._new_mean = tf.placeholder(shape=shape, dtype=tf.float64)
self._new_var = tf.placeholder(shape=shape, dtype=tf.float64)
self._new_count = tf.placeholder(shape=(), dtype=tf.float64)
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
self._mean = tf.get_variable('mean', initializer=np.zeros(shape, 'float64'), dtype=tf.float64)
self._var = tf.get_variable('std', initializer=np.ones(shape, 'float64'), dtype=tf.float64)
self._count = tf.get_variable('count', initializer=np.full((), epsilon, 'float64'), dtype=tf.float64)
self.update_ops = tf.group([
self._var.assign(self._new_var),
self._mean.assign(self._new_mean),
self._count.assign(self._new_count)
])
sess.run(tf.variables_initializer([self._mean, self._var, self._count]))
self.sess = sess
self._set_mean_var_count()
def _set_mean_var_count(self):
self.mean, self.var, self.count = self.sess.run([self._mean, self._var, self._count])
def update(self, x):
batch_mean = np.mean(x, axis=0)
batch_var = np.var(x, axis=0)
batch_count = x.shape[0]
new_mean, new_var, new_count = update_mean_var_count_from_moments(self.mean, self.var, self.count, batch_mean, batch_var, batch_count)
self.sess.run(self.update_ops, feed_dict={
self._new_mean: new_mean,
self._new_var: new_var,
self._new_count: new_count
})
self._set_mean_var_count()
def test_runningmeanstd():
for (x1, x2, x3) in [
(np.random.randn(3), np.random.randn(4), np.random.randn(5)),
(np.random.randn(3,2), np.random.randn(4,2), np.random.randn(5,2)),
]:
rms = RunningMeanStd(epsilon=0.0, shape=x1.shape[1:])
x = np.concatenate([x1, x2, x3], axis=0)
ms1 = [x.mean(axis=0), x.var(axis=0)]
rms.update(x1)
rms.update(x2)
rms.update(x3)
ms2 = [rms.mean, rms.var]
np.testing.assert_allclose(ms1, ms2)
def test_tf_runningmeanstd():
for (x1, x2, x3) in [
(np.random.randn(3), np.random.randn(4), np.random.randn(5)),
(np.random.randn(3,2), np.random.randn(4,2), np.random.randn(5,2)),
]:
rms = TfRunningMeanStd(epsilon=0.0, shape=x1.shape[1:], scope='running_mean_std' + str(np.random.randint(0, 128)))
x = np.concatenate([x1, x2, x3], axis=0)
ms1 = [x.mean(axis=0), x.var(axis=0)]
rms.update(x1)
rms.update(x2)
rms.update(x3)
ms2 = [rms.mean, rms.var]
np.testing.assert_allclose(ms1, ms2)
def profile_tf_runningmeanstd():
import time
from ppo.baselines.common import tf_util
tf_util.get_session( config=tf.ConfigProto(
inter_op_parallelism_threads=1,
intra_op_parallelism_threads=1,
allow_soft_placement=True
))
x = np.random.random((376,))
n_trials = 10000
rms = RunningMeanStd()
tfrms = TfRunningMeanStd()
tic1 = time.time()
for _ in range(n_trials):
rms.update(x)
tic2 = time.time()
for _ in range(n_trials):
tfrms.update(x)
tic3 = time.time()
print('rms update time ({} trials): {} s'.format(n_trials, tic2 - tic1))
print('tfrms update time ({} trials): {} s'.format(n_trials, tic3 - tic2))
tic1 = time.time()
for _ in range(n_trials):
z1 = rms.mean
tic2 = time.time()
for _ in range(n_trials):
z2 = tfrms.mean
assert z1 == z2
tic3 = time.time()
print('rms get mean time ({} trials): {} s'.format(n_trials, tic2 - tic1))
print('tfrms get mean time ({} trials): {} s'.format(n_trials, tic3 - tic2))
'''
options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) #pylint: disable=E1101
run_metadata = tf.RunMetadata()
profile_opts = dict(options=options, run_metadata=run_metadata)
from tensorflow.python.client import timeline
fetched_timeline = timeline.Timeline(run_metadata.step_stats) #pylint: disable=E1101
chrome_trace = fetched_timeline.generate_chrome_trace_format()
outfile = '/tmp/timeline.json'
with open(outfile, 'wt') as f:
f.write(chrome_trace)
print(f'Successfully saved profile to {outfile}. Exiting.')
exit(0)
'''
if __name__ == '__main__':
profile_tf_runningmeanstd() | ytopt | /ytopt-0.0.1.tar.gz/ytopt-0.0.1/ppo/baselines/common/running_mean_std.py | running_mean_std.py |
import numpy as np
import tensorflow as tf
from ppo.baselines.a2c import utils
from ppo.baselines.a2c.utils import conv, fc, conv_to_fc, batch_to_seq, seq_to_batch
from ppo.baselines.common.mpi_running_mean_std import RunningMeanStd
import tensorflow.contrib.layers as layers
mapping = {}
def register(name):
def _thunk(func):
mapping[name] = func
return func
return _thunk
def nature_cnn(unscaled_images, **conv_kwargs):
"""
CNN from Nature paper.
"""
scaled_images = tf.cast(unscaled_images, tf.float32) / 255.
activ = tf.nn.relu
h = activ(conv(scaled_images, 'c1', nf=32, rf=8, stride=4, init_scale=np.sqrt(2),
**conv_kwargs))
h2 = activ(conv(h, 'c2', nf=64, rf=4, stride=2, init_scale=np.sqrt(2), **conv_kwargs))
h3 = activ(conv(h2, 'c3', nf=64, rf=3, stride=1, init_scale=np.sqrt(2), **conv_kwargs))
h3 = conv_to_fc(h3)
return activ(fc(h3, 'fc1', nh=512, init_scale=np.sqrt(2)))
@register("mlp")
def mlp(num_layers=2, num_hidden=64, activation=tf.tanh, layer_norm=False):
"""
Stack of fully-connected layers to be used in a policy / q-function approximator
Parameters:
----------
num_layers: int number of fully-connected layers (default: 2)
num_hidden: int size of fully-connected layers (default: 64)
activation: activation function (default: tf.tanh)
Returns:
-------
function that builds fully connected network with a given input tensor / placeholder
"""
def network_fn(X):
h = tf.layers.flatten(X)
for i in range(num_layers):
h = fc(h, 'mlp_fc{}'.format(i), nh=num_hidden, init_scale=np.sqrt(2))
if layer_norm:
h = tf.contrib.layers.layer_norm(h, center=True, scale=True)
h = activation(h)
return h
return network_fn
@register("cnn")
def cnn(**conv_kwargs):
def network_fn(X):
return nature_cnn(X, **conv_kwargs)
return network_fn
@register("cnn_small")
def cnn_small(**conv_kwargs):
def network_fn(X):
h = tf.cast(X, tf.float32) / 255.
activ = tf.nn.relu
h = activ(conv(h, 'c1', nf=8, rf=8, stride=4, init_scale=np.sqrt(2), **conv_kwargs))
h = activ(conv(h, 'c2', nf=16, rf=4, stride=2, init_scale=np.sqrt(2), **conv_kwargs))
h = conv_to_fc(h)
h = activ(fc(h, 'fc1', nh=128, init_scale=np.sqrt(2)))
return h
return network_fn
@register("lstm")
def lstm(nlstm=128, layer_norm=False):
"""
Builds LSTM (Long-Short Term Memory) network to be used in a policy.
Note that the resulting function returns not only the output of the LSTM
(i.e. hidden state of lstm for each step in the sequence), but also a dictionary
with auxiliary tensors to be set as policy attributes.
Specifically,
S is a placeholder to feed current state (LSTM state has to be managed outside policy)
M is a placeholder for the mask (used to mask out observations after the end of the episode, but can be used for other purposes too)
initial_state is a numpy array containing initial lstm state (usually zeros)
state is the output LSTM state (to be fed into S at the next call)
An example of usage of lstm-based policy can be found here: common/tests/test_doc_examples.py/test_lstm_example
Parameters:
----------
nlstm: int LSTM hidden state size
layer_norm: bool if True, layer-normalized version of LSTM is used
Returns:
-------
function that builds LSTM with a given input tensor / placeholder
"""
def network_fn(X, nenv=1):
nbatch = X.shape[0]
nsteps = nbatch // nenv
h = tf.layers.flatten(X)
M = tf.placeholder(tf.float32, [nbatch]) #mask (done t-1)
S = tf.placeholder(tf.float32, [nenv, 2*nlstm]) #states
xs = batch_to_seq(h, nenv, nsteps)
ms = batch_to_seq(M, nenv, nsteps)
if layer_norm:
h5, snew = utils.lnlstm(xs, ms, S, scope='lnlstm', nh=nlstm)
else:
h5, snew = utils.lstm(xs, ms, S, scope='lstm', nh=nlstm)
h = seq_to_batch(h5)
initial_state = np.zeros(S.shape.as_list(), dtype=float)
return h, {'S':S, 'M':M, 'state':snew, 'initial_state':initial_state}
return network_fn
@register("cnn_lstm")
def cnn_lstm(nlstm=128, layer_norm=False, **conv_kwargs):
def network_fn(X, nenv=1):
nbatch = X.shape[0]
nsteps = nbatch // nenv
h = nature_cnn(X, **conv_kwargs)
M = tf.placeholder(tf.float32, [nbatch]) #mask (done t-1)
S = tf.placeholder(tf.float32, [nenv, 2*nlstm]) #states
xs = batch_to_seq(h, nenv, nsteps)
ms = batch_to_seq(M, nenv, nsteps)
if layer_norm:
h5, snew = utils.lnlstm(xs, ms, S, scope='lnlstm', nh=nlstm)
else:
h5, snew = utils.lstm(xs, ms, S, scope='lstm', nh=nlstm)
h = seq_to_batch(h5)
initial_state = np.zeros(S.shape.as_list(), dtype=float)
return h, {'S':S, 'M':M, 'state':snew, 'initial_state':initial_state}
return network_fn
@register("cnn_lnlstm")
def cnn_lnlstm(nlstm=128, **conv_kwargs):
return cnn_lstm(nlstm, layer_norm=True, **conv_kwargs)
@register("conv_only")
def conv_only(convs=[(32, 8, 4), (64, 4, 2), (64, 3, 1)], **conv_kwargs):
'''
convolutions-only net
Parameters:
----------
conv: list of triples (filter_number, filter_size, stride) specifying parameters for each layer.
Returns:
function that takes tensorflow tensor as input and returns the output of the last convolutional layer
'''
def network_fn(X):
out = tf.cast(X, tf.float32) / 255.
with tf.variable_scope("convnet"):
for num_outputs, kernel_size, stride in convs:
out = layers.convolution2d(out,
num_outputs=num_outputs,
kernel_size=kernel_size,
stride=stride,
activation_fn=tf.nn.relu,
**conv_kwargs)
return out
return network_fn
def _normalize_clip_observation(x, clip_range=[-5.0, 5.0]):
rms = RunningMeanStd(shape=x.shape[1:])
norm_x = tf.clip_by_value((x - rms.mean) / rms.std, min(clip_range), max(clip_range))
return norm_x, rms
def get_network_builder(name):
"""
If you want to register your own network outside models.py, you just need:
Usage Example:
-------------
from ppo.baselines.common.models import register
@register("your_network_name")
def your_network_define(**net_kwargs):
...
return network_fn
"""
if callable(name):
return name
elif name in mapping:
return mapping[name]
else:
raise ValueError('Unknown network type: {}'.format(name)) | ytopt | /ytopt-0.0.1.tar.gz/ytopt-0.0.1/ppo/baselines/common/models.py | models.py |
import joblib
import numpy as np
import tensorflow as tf # pylint: ignore-module
import copy
import os
import functools
import collections
import multiprocessing
def switch(condition, then_expression, else_expression):
"""Switches between two operations depending on a scalar value (int or bool).
Note that both `then_expression` and `else_expression`
should be symbolic tensors of the *same shape*.
# Arguments
condition: scalar tensor.
then_expression: TensorFlow operation.
else_expression: TensorFlow operation.
"""
x_shape = copy.copy(then_expression.get_shape())
x = tf.cond(tf.cast(condition, 'bool'),
lambda: then_expression,
lambda: else_expression)
x.set_shape(x_shape)
return x
# ================================================================
# Extras
# ================================================================
def lrelu(x, leak=0.2):
f1 = 0.5 * (1 + leak)
f2 = 0.5 * (1 - leak)
return f1 * x + f2 * abs(x)
# ================================================================
# Mathematical utils
# ================================================================
def huber_loss(x, delta=1.0):
"""Reference: https://en.wikipedia.org/wiki/Huber_loss"""
return tf.where(
tf.abs(x) < delta,
tf.square(x) * 0.5,
delta * (tf.abs(x) - 0.5 * delta)
)
# ================================================================
# Global session
# ================================================================
def get_session(config=None):
"""Get default session or create one with a given config"""
sess = tf.get_default_session()
if sess is None:
sess = make_session(config=config, make_default=True)
return sess
def make_session(config=None, num_cpu=None, make_default=False, graph=None):
"""Returns a session that will use <num_cpu> CPU's only"""
if num_cpu is None:
num_cpu = int(os.getenv('RCALL_NUM_CPU', multiprocessing.cpu_count()))
if config is None:
config = tf.ConfigProto(
allow_soft_placement=True,
inter_op_parallelism_threads=num_cpu,
intra_op_parallelism_threads=num_cpu)
config.gpu_options.allow_growth = True
if make_default:
return tf.InteractiveSession(config=config, graph=graph)
else:
return tf.Session(config=config, graph=graph)
def single_threaded_session():
"""Returns a session which will only use a single CPU"""
return make_session(num_cpu=1)
def in_session(f):
@functools.wraps(f)
def newfunc(*args, **kwargs):
with tf.Session():
f(*args, **kwargs)
return newfunc
ALREADY_INITIALIZED = set()
def initialize():
"""Initialize all the uninitialized variables in the global scope."""
new_variables = set(tf.global_variables()) - ALREADY_INITIALIZED
get_session().run(tf.variables_initializer(new_variables))
ALREADY_INITIALIZED.update(new_variables)
# ================================================================
# Model components
# ================================================================
def normc_initializer(std=1.0, axis=0):
def _initializer(shape, dtype=None, partition_info=None): # pylint: disable=W0613
out = np.random.randn(*shape).astype(dtype.as_numpy_dtype)
out *= std / np.sqrt(np.square(out).sum(axis=axis, keepdims=True))
return tf.constant(out)
return _initializer
def conv2d(x, num_filters, name, filter_size=(3, 3), stride=(1, 1), pad="SAME", dtype=tf.float32, collections=None,
summary_tag=None):
with tf.variable_scope(name):
stride_shape = [1, stride[0], stride[1], 1]
filter_shape = [filter_size[0], filter_size[1], int(x.get_shape()[3]), num_filters]
# there are "num input feature maps * filter height * filter width"
# inputs to each hidden unit
fan_in = intprod(filter_shape[:3])
# each unit in the lower layer receives a gradient from:
# "num output feature maps * filter height * filter width" /
# pooling size
fan_out = intprod(filter_shape[:2]) * num_filters
# initialize weights with random weights
w_bound = np.sqrt(6. / (fan_in + fan_out))
w = tf.get_variable("W", filter_shape, dtype, tf.random_uniform_initializer(-w_bound, w_bound),
collections=collections)
b = tf.get_variable("b", [1, 1, 1, num_filters], initializer=tf.zeros_initializer(),
collections=collections)
if summary_tag is not None:
tf.summary.image(summary_tag,
tf.transpose(tf.reshape(w, [filter_size[0], filter_size[1], -1, 1]),
[2, 0, 1, 3]),
max_images=10)
return tf.nn.conv2d(x, w, stride_shape, pad) + b
# ================================================================
# Theano-like Function
# ================================================================
def function(inputs, outputs, updates=None, givens=None):
"""Just like Theano function. Take a bunch of tensorflow placeholders and expressions
computed based on those placeholders and produces f(inputs) -> outputs. Function f takes
values to be fed to the input's placeholders and produces the values of the expressions
in outputs.
Input values can be passed in the same order as inputs or can be provided as kwargs based
on placeholder name (passed to constructor or accessible via placeholder.op.name).
Example:
x = tf.placeholder(tf.int32, (), name="x")
y = tf.placeholder(tf.int32, (), name="y")
z = 3 * x + 2 * y
lin = function([x, y], z, givens={y: 0})
with single_threaded_session():
initialize()
assert lin(2) == 6
assert lin(x=3) == 9
assert lin(2, 2) == 10
assert lin(x=2, y=3) == 12
Parameters
----------
inputs: [tf.placeholder, tf.constant, or object with make_feed_dict method]
list of input arguments
outputs: [tf.Variable] or tf.Variable
list of outputs or a single output to be returned from function. Returned
value will also have the same shape.
"""
if isinstance(outputs, list):
return _Function(inputs, outputs, updates, givens=givens)
elif isinstance(outputs, (dict, collections.OrderedDict)):
f = _Function(inputs, outputs.values(), updates, givens=givens)
return lambda *args, **kwargs: type(outputs)(zip(outputs.keys(), f(*args, **kwargs)))
else:
f = _Function(inputs, [outputs], updates, givens=givens)
return lambda *args, **kwargs: f(*args, **kwargs)[0]
class _Function(object):
def __init__(self, inputs, outputs, updates, givens):
for inpt in inputs:
if not hasattr(inpt, 'make_feed_dict') and not (type(inpt) is tf.Tensor and len(inpt.op.inputs) == 0):
assert False, "inputs should all be placeholders, constants, or have a make_feed_dict method"
self.inputs = inputs
updates = updates or []
self.update_group = tf.group(*updates)
self.outputs_update = list(outputs) + [self.update_group]
self.givens = {} if givens is None else givens
def _feed_input(self, feed_dict, inpt, value):
if hasattr(inpt, 'make_feed_dict'):
feed_dict.update(inpt.make_feed_dict(value))
else:
feed_dict[inpt] = adjust_shape(inpt, value)
def __call__(self, *args):
assert len(args) <= len(self.inputs), "Too many arguments provided"
feed_dict = {}
# Update the args
for inpt, value in zip(self.inputs, args):
self._feed_input(feed_dict, inpt, value)
# Update feed dict with givens.
for inpt in self.givens:
feed_dict[inpt] = adjust_shape(inpt, feed_dict.get(inpt, self.givens[inpt]))
results = get_session().run(self.outputs_update, feed_dict=feed_dict)[:-1]
return results
# ================================================================
# Flat vectors
# ================================================================
def var_shape(x):
out = x.get_shape().as_list()
assert all(isinstance(a, int) for a in out), \
"shape function assumes that shape is fully known"
return out
def numel(x):
return intprod(var_shape(x))
def intprod(x):
return int(np.prod(x))
def flatgrad(loss, var_list, clip_norm=None):
grads = tf.gradients(loss, var_list)
if clip_norm is not None:
grads = [tf.clip_by_norm(grad, clip_norm=clip_norm) for grad in grads]
return tf.concat(axis=0, values=[
tf.reshape(grad if grad is not None else tf.zeros_like(v), [numel(v)])
for (v, grad) in zip(var_list, grads)
])
class SetFromFlat(object):
def __init__(self, var_list, dtype=tf.float32):
assigns = []
shapes = list(map(var_shape, var_list))
total_size = np.sum([intprod(shape) for shape in shapes])
self.theta = theta = tf.placeholder(dtype, [total_size])
start = 0
assigns = []
for (shape, v) in zip(shapes, var_list):
size = intprod(shape)
assigns.append(tf.assign(v, tf.reshape(theta[start:start + size], shape)))
start += size
self.op = tf.group(*assigns)
def __call__(self, theta):
tf.get_default_session().run(self.op, feed_dict={self.theta: theta})
class GetFlat(object):
def __init__(self, var_list):
self.op = tf.concat(axis=0, values=[tf.reshape(v, [numel(v)]) for v in var_list])
def __call__(self):
return tf.get_default_session().run(self.op)
def flattenallbut0(x):
return tf.reshape(x, [-1, intprod(x.get_shape().as_list()[1:])])
# =============================================================
# TF placeholders management
# ============================================================
_PLACEHOLDER_CACHE = {} # name -> (placeholder, dtype, shape)
def get_placeholder(name, dtype, shape):
if name in _PLACEHOLDER_CACHE:
out, dtype1, shape1 = _PLACEHOLDER_CACHE[name]
if out.graph == tf.get_default_graph():
assert dtype1 == dtype and shape1 == shape, \
'Placeholder with name {} has already been registered and has shape {}, different from requested {}'.format(name, shape1, shape)
return out
out = tf.placeholder(dtype=dtype, shape=shape, name=name)
_PLACEHOLDER_CACHE[name] = (out, dtype, shape)
return out
def get_placeholder_cached(name):
return _PLACEHOLDER_CACHE[name][0]
# ================================================================
# Diagnostics
# ================================================================
def display_var_info(vars):
from ppo.baselines import logger
count_params = 0
for v in vars:
name = v.name
if "/Adam" in name or "beta1_power" in name or "beta2_power" in name: continue
v_params = np.prod(v.shape.as_list())
count_params += v_params
if "/b:" in name or "/biases" in name: continue # Wx+b, bias is not interesting to look at => count params, but not print
logger.info(" %s%s %i params %s" % (name, " "*(55-len(name)), v_params, str(v.shape)))
logger.info("Total model parameters: %0.2f million" % (count_params*1e-6))
def get_available_gpus():
# recipe from here:
# https://stackoverflow.com/questions/38559755/how-to-get-current-available-gpus-in-tensorflow?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
from tensorflow.python.client import device_lib
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type == 'GPU']
# ================================================================
# Saving variables
# ================================================================
def load_state(fname, sess=None):
from ppo.baselines import logger
logger.warn('load_state method is deprecated, please use load_variables instead')
sess = sess or get_session()
saver = tf.train.Saver()
saver.restore(tf.get_default_session(), fname)
def save_state(fname, sess=None):
from ppo.baselines import logger
logger.warn('save_state method is deprecated, please use save_variables instead')
sess = sess or get_session()
dirname = os.path.dirname(fname)
if any(dirname):
os.makedirs(dirname, exist_ok=True)
saver = tf.train.Saver()
saver.save(tf.get_default_session(), fname)
# The methods above and below are clearly doing the same thing, and in a rather similar way
# TODO: ensure there is no subtle differences and remove one
def save_variables(save_path, variables=None, sess=None):
sess = sess or get_session()
variables = variables or tf.trainable_variables()
ps = sess.run(variables)
save_dict = {v.name: value for v, value in zip(variables, ps)}
dirname = os.path.dirname(save_path)
if any(dirname):
os.makedirs(dirname, exist_ok=True)
joblib.dump(save_dict, save_path)
def load_variables(load_path, variables=None, sess=None):
sess = sess or get_session()
variables = variables or tf.trainable_variables()
loaded_params = joblib.load(os.path.expanduser(load_path))
restores = []
if isinstance(loaded_params, list):
assert len(loaded_params) == len(variables), 'number of variables loaded mismatches len(variables)'
for d, v in zip(loaded_params, variables):
restores.append(v.assign(d))
else:
for v in variables:
restores.append(v.assign(loaded_params[v.name]))
sess.run(restores)
# ================================================================
# Shape adjustment for feeding into tf placeholders
# ================================================================
def adjust_shape(placeholder, data):
'''
adjust shape of the data to the shape of the placeholder if possible.
If shape is incompatible, AssertionError is thrown
Parameters:
placeholder tensorflow input placeholder
data input data to be (potentially) reshaped to be fed into placeholder
Returns:
reshaped data
'''
if not isinstance(data, np.ndarray) and not isinstance(data, list):
return data
if isinstance(data, list):
data = np.array(data)
placeholder_shape = [x or -1 for x in placeholder.shape.as_list()]
assert _check_shape(placeholder_shape, data.shape), \
'Shape of data {} is not compatible with shape of the placeholder {}'.format(data.shape, placeholder_shape)
return np.reshape(data, placeholder_shape)
def _check_shape(placeholder_shape, data_shape):
''' check if two shapes are compatible (i.e. differ only by dimensions of size 1, or by the batch dimension)'''
return True
squeezed_placeholder_shape = _squeeze_shape(placeholder_shape)
squeezed_data_shape = _squeeze_shape(data_shape)
for i, s_data in enumerate(squeezed_data_shape):
s_placeholder = squeezed_placeholder_shape[i]
if s_placeholder != -1 and s_data != s_placeholder:
return False
return True
def _squeeze_shape(shape):
return [x for x in shape if x != 1]
# ================================================================
# Tensorboard interfacing
# ================================================================
def launch_tensorboard_in_background(log_dir):
'''
To log the Tensorflow graph when using rl-algs
algorithms, you can run the following code
in your main script:
import threading, time
def start_tensorboard(session):
time.sleep(10) # Wait until graph is setup
tb_path = osp.join(logger.get_dir(), 'tb')
summary_writer = tf.summary.FileWriter(tb_path, graph=session.graph)
summary_op = tf.summary.merge_all()
launch_tensorboard_in_background(tb_path)
session = tf.get_default_session()
t = threading.Thread(target=start_tensorboard, args=([session]))
t.start()
'''
import subprocess
subprocess.Popen(['tensorboard', '--logdir', log_dir]) | ytopt | /ytopt-0.0.1.tar.gz/ytopt-0.0.1/ppo/baselines/common/tf_util.py | tf_util.py |
import operator
class SegmentTree(object):
def __init__(self, capacity, operation, neutral_element):
"""Build a Segment Tree data structure.
https://en.wikipedia.org/wiki/Segment_tree
Can be used as regular array, but with two
important differences:
a) setting item's value is slightly slower.
It is O(lg capacity) instead of O(1).
b) user has access to an efficient ( O(log segment size) )
`reduce` operation which reduces `operation` over
a contiguous subsequence of items in the array.
Paramters
---------
capacity: int
Total size of the array - must be a power of two.
operation: lambda obj, obj -> obj
and operation for combining elements (eg. sum, max)
must form a mathematical group together with the set of
possible values for array elements (i.e. be associative)
neutral_element: obj
neutral element for the operation above. eg. float('-inf')
for max and 0 for sum.
"""
assert capacity > 0 and capacity & (capacity - 1) == 0, "capacity must be positive and a power of 2."
self._capacity = capacity
self._value = [neutral_element for _ in range(2 * capacity)]
self._operation = operation
def _reduce_helper(self, start, end, node, node_start, node_end):
if start == node_start and end == node_end:
return self._value[node]
mid = (node_start + node_end) // 2
if end <= mid:
return self._reduce_helper(start, end, 2 * node, node_start, mid)
else:
if mid + 1 <= start:
return self._reduce_helper(start, end, 2 * node + 1, mid + 1, node_end)
else:
return self._operation(
self._reduce_helper(start, mid, 2 * node, node_start, mid),
self._reduce_helper(mid + 1, end, 2 * node + 1, mid + 1, node_end)
)
def reduce(self, start=0, end=None):
"""Returns result of applying `self.operation`
to a contiguous subsequence of the array.
self.operation(arr[start], operation(arr[start+1], operation(... arr[end])))
Parameters
----------
start: int
beginning of the subsequence
end: int
end of the subsequences
Returns
-------
reduced: obj
result of reducing self.operation over the specified range of array elements.
"""
if end is None:
end = self._capacity
if end < 0:
end += self._capacity
end -= 1
return self._reduce_helper(start, end, 1, 0, self._capacity - 1)
def __setitem__(self, idx, val):
# index of the leaf
idx += self._capacity
self._value[idx] = val
idx //= 2
while idx >= 1:
self._value[idx] = self._operation(
self._value[2 * idx],
self._value[2 * idx + 1]
)
idx //= 2
def __getitem__(self, idx):
assert 0 <= idx < self._capacity
return self._value[self._capacity + idx]
class SumSegmentTree(SegmentTree):
def __init__(self, capacity):
super(SumSegmentTree, self).__init__(
capacity=capacity,
operation=operator.add,
neutral_element=0.0
)
def sum(self, start=0, end=None):
"""Returns arr[start] + ... + arr[end]"""
return super(SumSegmentTree, self).reduce(start, end)
def find_prefixsum_idx(self, prefixsum):
"""Find the highest index `i` in the array such that
sum(arr[0] + arr[1] + ... + arr[i - i]) <= prefixsum
if array values are probabilities, this function
allows to sample indexes according to the discrete
probability efficiently.
Parameters
----------
perfixsum: float
upperbound on the sum of array prefix
Returns
-------
idx: int
highest index satisfying the prefixsum constraint
"""
assert 0 <= prefixsum <= self.sum() + 1e-5
idx = 1
while idx < self._capacity: # while non-leaf
if self._value[2 * idx] > prefixsum:
idx = 2 * idx
else:
prefixsum -= self._value[2 * idx]
idx = 2 * idx + 1
return idx - self._capacity
class MinSegmentTree(SegmentTree):
def __init__(self, capacity):
super(MinSegmentTree, self).__init__(
capacity=capacity,
operation=min,
neutral_element=float('inf')
)
def min(self, start=0, end=None):
"""Returns min(arr[start], ..., arr[end])"""
return super(MinSegmentTree, self).reduce(start, end) | ytopt | /ytopt-0.0.1.tar.gz/ytopt-0.0.1/ppo/baselines/common/segment_tree.py | segment_tree.py |
class Schedule(object):
def value(self, t):
"""Value of the schedule at time t"""
raise NotImplementedError()
class ConstantSchedule(object):
def __init__(self, value):
"""Value remains constant over time.
Parameters
----------
value: float
Constant value of the schedule
"""
self._v = value
def value(self, t):
"""See Schedule.value"""
return self._v
def linear_interpolation(l, r, alpha):
return l + alpha * (r - l)
class PiecewiseSchedule(object):
def __init__(self, endpoints, interpolation=linear_interpolation, outside_value=None):
"""Piecewise schedule.
endpoints: [(int, int)]
list of pairs `(time, value)` meanining that schedule should output
`value` when `t==time`. All the values for time must be sorted in
an increasing order. When t is between two times, e.g. `(time_a, value_a)`
and `(time_b, value_b)`, such that `time_a <= t < time_b` then value outputs
`interpolation(value_a, value_b, alpha)` where alpha is a fraction of
time passed between `time_a` and `time_b` for time `t`.
interpolation: lambda float, float, float: float
a function that takes value to the left and to the right of t according
to the `endpoints`. Alpha is the fraction of distance from left endpoint to
right endpoint that t has covered. See linear_interpolation for example.
outside_value: float
if the value is requested outside of all the intervals sepecified in
`endpoints` this value is returned. If None then AssertionError is
raised when outside value is requested.
"""
idxes = [e[0] for e in endpoints]
assert idxes == sorted(idxes)
self._interpolation = interpolation
self._outside_value = outside_value
self._endpoints = endpoints
def value(self, t):
"""See Schedule.value"""
for (l_t, l), (r_t, r) in zip(self._endpoints[:-1], self._endpoints[1:]):
if l_t <= t and t < r_t:
alpha = float(t - l_t) / (r_t - l_t)
return self._interpolation(l, r, alpha)
# t does not belong to any of the pieces, so doom.
assert self._outside_value is not None
return self._outside_value
class LinearSchedule(object):
def __init__(self, schedule_timesteps, final_p, initial_p=1.0):
"""Linear interpolation between initial_p and final_p over
schedule_timesteps. After this many timesteps pass final_p is
returned.
Parameters
----------
schedule_timesteps: int
Number of timesteps for which to linearly anneal initial_p
to final_p
initial_p: float
initial output value
final_p: float
final output value
"""
self.schedule_timesteps = schedule_timesteps
self.final_p = final_p
self.initial_p = initial_p
def value(self, t):
"""See Schedule.value"""
fraction = min(float(t) / self.schedule_timesteps, 1.0)
return self.initial_p + fraction * (self.final_p - self.initial_p) | ytopt | /ytopt-0.0.1.tar.gz/ytopt-0.0.1/ppo/baselines/common/schedules.py | schedules.py |
import numpy as np
from multiprocessing import Process, Pipe
from . import VecEnv, CloudpickleWrapper
def worker(remote, parent_remote, env_fn_wrapper):
parent_remote.close()
env = env_fn_wrapper.x()
try:
while True:
cmd, data = remote.recv()
if cmd == 'step':
ob, reward, done, info = env.step(data)
if done:
ob = env.reset()
remote.send((ob, reward, done, info))
elif cmd == 'reset':
ob = env.reset()
remote.send(ob)
elif cmd == 'render':
remote.send(env.render(mode='rgb_array'))
elif cmd == 'close':
remote.close()
break
elif cmd == 'get_spaces':
remote.send((env.observation_space, env.action_space))
else:
raise NotImplementedError
except KeyboardInterrupt:
print('SubprocVecEnv worker: got KeyboardInterrupt')
finally:
env.close()
class SubprocVecEnv(VecEnv):
"""
VecEnv that runs multiple environments in parallel in subproceses and communicates with them via pipes.
Recommended to use when num_envs > 1 and step() can be a bottleneck.
"""
def __init__(self, env_fns, spaces=None):
"""
Arguments:
env_fns: iterable of callables - functions that create environments to run in subprocesses. Need to be cloud-pickleable
"""
self.waiting = False
self.closed = False
nenvs = len(env_fns)
self.remotes, self.work_remotes = zip(*[Pipe() for _ in range(nenvs)])
self.ps = [Process(target=worker, args=(work_remote, remote, CloudpickleWrapper(env_fn)))
for (work_remote, remote, env_fn) in zip(self.work_remotes, self.remotes, env_fns)]
for p in self.ps:
p.daemon = True # if the main process crashes, we should not cause things to hang
p.start()
for remote in self.work_remotes:
remote.close()
self.remotes[0].send(('get_spaces', None))
observation_space, action_space = self.remotes[0].recv()
self.viewer = None
VecEnv.__init__(self, len(env_fns), observation_space, action_space)
def step_async(self, actions):
self._assert_not_closed()
for remote, action in zip(self.remotes, actions):
remote.send(('step', action))
self.waiting = True
def step_wait(self):
self._assert_not_closed()
results = [remote.recv() for remote in self.remotes]
self.waiting = False
obs, rews, dones, infos = zip(*results)
return np.stack(obs), np.stack(rews), np.stack(dones), infos
def reset(self):
self._assert_not_closed()
for remote in self.remotes:
remote.send(('reset', None))
return np.stack([remote.recv() for remote in self.remotes])
def close_extras(self):
self.closed = True
if self.waiting:
for remote in self.remotes:
remote.recv()
for remote in self.remotes:
remote.send(('close', None))
for p in self.ps:
p.join()
def get_images(self):
self._assert_not_closed()
for pipe in self.remotes:
pipe.send(('render', None))
imgs = [pipe.recv() for pipe in self.remotes]
return imgs
def _assert_not_closed(self):
assert not self.closed, "Trying to operate on a SubprocVecEnv after calling close()" | ytopt | /ytopt-0.0.1.tar.gz/ytopt-0.0.1/ppo/baselines/common/vec_env/subproc_vec_env.py | subproc_vec_env.py |
import numpy as np
from gym import spaces
from . import VecEnv
from .util import copy_obs_dict, dict_to_obs, obs_space_info
class DummyVecEnv(VecEnv):
"""
VecEnv that does runs multiple environments sequentially, that is,
the step and reset commands are send to one environment at a time.
Useful when debugging and when num_env == 1 (in the latter case,
avoids communication overhead)
"""
def __init__(self, env_fns):
"""
Arguments:
env_fns: iterable of callables functions that build environments
"""
self.envs = [fn() for fn in env_fns]
env = self.envs[0]
VecEnv.__init__(self, len(env_fns), env.observation_space, env.action_space)
obs_space = env.observation_space
self.keys, shapes, dtypes = obs_space_info(obs_space)
self.buf_obs = { k: np.zeros((self.num_envs,) + tuple(shapes[k]), dtype=dtypes[k]) for k in self.keys }
self.buf_dones = np.zeros((self.num_envs,), dtype=np.bool)
self.buf_rews = np.zeros((self.num_envs,), dtype=np.float32)
self.buf_infos = [{} for _ in range(self.num_envs)]
self.actions = None
def step_async(self, actions):
listify = True
try:
if len(actions) == self.num_envs:
listify = False
except TypeError:
pass
if not listify:
self.actions = actions
else:
assert self.num_envs == 1, "actions {} is either not a list or has a wrong size - cannot match to {} environments".format(actions, self.num_envs)
self.actions = [actions]
def step_wait(self):
for e in range(self.num_envs):
action = self.actions[e]
if isinstance(self.envs[e].action_space, spaces.Discrete):
action = int(action)
obs, self.buf_rews[e], self.buf_dones[e], self.buf_infos[e] = self.envs[e].step(action)
if self.buf_dones[e]:
obs = self.envs[e].reset()
self._save_obs(e, obs)
return (self._obs_from_buf(), np.copy(self.buf_rews), np.copy(self.buf_dones),
self.buf_infos.copy())
def reset(self):
for e in range(self.num_envs):
obs = self.envs[e].reset()
self._save_obs(e, obs)
return self._obs_from_buf()
def _save_obs(self, e, obs):
for k in self.keys:
if k is None:
self.buf_obs[k][e] = obs
else:
self.buf_obs[k][e] = obs[k]
def _obs_from_buf(self):
return dict_to_obs(copy_obs_dict(self.buf_obs))
def get_images(self):
return [env.render(mode='rgb_array') for env in self.envs]
def render(self, mode='human'):
if self.num_envs == 1:
self.envs[0].render(mode=mode)
else:
super().render(mode=mode) | ytopt | /ytopt-0.0.1.tar.gz/ytopt-0.0.1/ppo/baselines/common/vec_env/dummy_vec_env.py | dummy_vec_env.py |
from multiprocessing import Pipe, Array, Process
import numpy as np
from . import VecEnv, CloudpickleWrapper
import ctypes
from ppo.baselines import logger
from .util import dict_to_obs, obs_space_info, obs_to_dict
_NP_TO_CT = {np.float32: ctypes.c_float,
np.int32: ctypes.c_int32,
np.int8: ctypes.c_int8,
np.uint8: ctypes.c_char,
np.bool: ctypes.c_bool}
class ShmemVecEnv(VecEnv):
"""
Optimized version of SubprocVecEnv that uses shared variables to communicate observations.
"""
def __init__(self, env_fns, spaces=None):
"""
If you don't specify observation_space, we'll have to create a dummy
environment to get it.
"""
if spaces:
observation_space, action_space = spaces
else:
logger.log('Creating dummy env object to get spaces')
with logger.scoped_configure(format_strs=[]):
dummy = env_fns[0]()
observation_space, action_space = dummy.observation_space, dummy.action_space
dummy.close()
del dummy
VecEnv.__init__(self, len(env_fns), observation_space, action_space)
self.obs_keys, self.obs_shapes, self.obs_dtypes = obs_space_info(observation_space)
self.obs_bufs = [
{k: Array(_NP_TO_CT[self.obs_dtypes[k].type], int(np.prod(self.obs_shapes[k]))) for k in self.obs_keys}
for _ in env_fns]
self.parent_pipes = []
self.procs = []
for env_fn, obs_buf in zip(env_fns, self.obs_bufs):
wrapped_fn = CloudpickleWrapper(env_fn)
parent_pipe, child_pipe = Pipe()
proc = Process(target=_subproc_worker,
args=(child_pipe, parent_pipe, wrapped_fn, obs_buf, self.obs_shapes, self.obs_dtypes, self.obs_keys))
proc.daemon = True
self.procs.append(proc)
self.parent_pipes.append(parent_pipe)
proc.start()
child_pipe.close()
self.waiting_step = False
self.viewer = None
def reset(self):
if self.waiting_step:
logger.warn('Called reset() while waiting for the step to complete')
self.step_wait()
for pipe in self.parent_pipes:
pipe.send(('reset', None))
return self._decode_obses([pipe.recv() for pipe in self.parent_pipes])
def step_async(self, actions):
assert len(actions) == len(self.parent_pipes)
for pipe, act in zip(self.parent_pipes, actions):
pipe.send(('step', act))
def step_wait(self):
outs = [pipe.recv() for pipe in self.parent_pipes]
obs, rews, dones, infos = zip(*outs)
return self._decode_obses(obs), np.array(rews), np.array(dones), infos
def close_extras(self):
if self.waiting_step:
self.step_wait()
for pipe in self.parent_pipes:
pipe.send(('close', None))
for pipe in self.parent_pipes:
pipe.recv()
pipe.close()
for proc in self.procs:
proc.join()
def get_images(self, mode='human'):
for pipe in self.parent_pipes:
pipe.send(('render', None))
return [pipe.recv() for pipe in self.parent_pipes]
def _decode_obses(self, obs):
result = {}
for k in self.obs_keys:
bufs = [b[k] for b in self.obs_bufs]
o = [np.frombuffer(b.get_obj(), dtype=self.obs_dtypes[k]).reshape(self.obs_shapes[k]) for b in bufs]
result[k] = np.array(o)
return dict_to_obs(result)
def _subproc_worker(pipe, parent_pipe, env_fn_wrapper, obs_bufs, obs_shapes, obs_dtypes, keys):
"""
Control a single environment instance using IPC and
shared memory.
"""
def _write_obs(maybe_dict_obs):
flatdict = obs_to_dict(maybe_dict_obs)
for k in keys:
dst = obs_bufs[k].get_obj()
dst_np = np.frombuffer(dst, dtype=obs_dtypes[k]).reshape(obs_shapes[k]) # pylint: disable=W0212
np.copyto(dst_np, flatdict[k])
env = env_fn_wrapper.x()
parent_pipe.close()
try:
while True:
cmd, data = pipe.recv()
if cmd == 'reset':
pipe.send(_write_obs(env.reset()))
elif cmd == 'step':
obs, reward, done, info = env.step(data)
if done:
obs = env.reset()
pipe.send((_write_obs(obs), reward, done, info))
elif cmd == 'render':
pipe.send(env.render(mode='rgb_array'))
elif cmd == 'close':
pipe.send(None)
break
else:
raise RuntimeError('Got unrecognized cmd %s' % cmd)
except KeyboardInterrupt:
print('ShmemVecEnv worker: got KeyboardInterrupt')
finally:
env.close() | ytopt | /ytopt-0.0.1.tar.gz/ytopt-0.0.1/ppo/baselines/common/vec_env/shmem_vec_env.py | shmem_vec_env.py |
from abc import ABC, abstractmethod
from ppo.baselines.common.tile_images import tile_images
class AlreadySteppingError(Exception):
"""
Raised when an asynchronous step is running while
step_async() is called again.
"""
def __init__(self):
msg = 'already running an async step'
Exception.__init__(self, msg)
class NotSteppingError(Exception):
"""
Raised when an asynchronous step is not running but
step_wait() is called.
"""
def __init__(self):
msg = 'not running an async step'
Exception.__init__(self, msg)
class VecEnv(ABC):
"""
An abstract asynchronous, vectorized environment.
Used to batch data from multiple copies of an environment, so that
each observation becomes an batch of observations, and expected action is a batch of actions to
be applied per-environment.
"""
closed = False
viewer = None
def __init__(self, num_envs, observation_space, action_space):
self.num_envs = num_envs
self.observation_space = observation_space
self.action_space = action_space
@abstractmethod
def reset(self):
"""
Reset all the environments and return an array of
observations, or a dict of observation arrays.
If step_async is still doing work, that work will
be cancelled and step_wait() should not be called
until step_async() is invoked again.
"""
pass
@abstractmethod
def step_async(self, actions):
"""
Tell all the environments to start taking a step
with the given actions.
Call step_wait() to get the results of the step.
You should not call this if a step_async run is
already pending.
"""
pass
@abstractmethod
def step_wait(self):
"""
Wait for the step taken with step_async().
Returns (obs, rews, dones, infos):
- obs: an array of observations, or a dict of
arrays of observations.
- rews: an array of rewards
- dones: an array of "episode done" booleans
- infos: a sequence of info objects
"""
pass
def close_extras(self):
"""
Clean up the extra resources, beyond what's in this base class.
Only runs when not self.closed.
"""
pass
def close(self):
if self.closed:
return
if self.viewer is not None:
self.viewer.close()
self.close_extras()
self.closed = True
def step(self, actions):
"""
Step the environments synchronously.
This is available for backwards compatibility.
"""
self.step_async(actions)
return self.step_wait()
def render(self, mode='human'):
imgs = self.get_images()
bigimg = tile_images(imgs)
if mode == 'human':
self.get_viewer().imshow(bigimg)
elif mode == 'rgb_array':
return bigimg
else:
raise NotImplementedError
def get_images(self):
"""
Return RGB images from each environment
"""
raise NotImplementedError
@property
def unwrapped(self):
if isinstance(self, VecEnvWrapper):
return self.venv.unwrapped
else:
return self
def get_viewer(self):
if self.viewer is None:
from gym.envs.classic_control import rendering
self.viewer = rendering.SimpleImageViewer()
return self.viewer
class VecEnvWrapper(VecEnv):
"""
An environment wrapper that applies to an entire batch
of environments at once.
"""
def __init__(self, venv, observation_space=None, action_space=None):
self.venv = venv
VecEnv.__init__(self,
num_envs=venv.num_envs,
observation_space=observation_space or venv.observation_space,
action_space=action_space or venv.action_space)
def step_async(self, actions):
self.venv.step_async(actions)
@abstractmethod
def reset(self):
pass
@abstractmethod
def step_wait(self):
pass
def close(self):
return self.venv.close()
def render(self, mode='human'):
return self.venv.render(mode=mode)
def get_images(self):
return self.venv.get_images()
class CloudpickleWrapper(object):
"""
Uses cloudpickle to serialize contents (otherwise multiprocessing tries to use pickle)
"""
def __init__(self, x):
self.x = x
def __getstate__(self):
import cloudpickle
return cloudpickle.dumps(self.x)
def __setstate__(self, ob):
import pickle
self.x = pickle.loads(ob) | ytopt | /ytopt-0.0.1.tar.gz/ytopt-0.0.1/ppo/baselines/common/vec_env/__init__.py | __init__.py |
from ._compat import PY2, text_type, long_type, JYTHON, IRONPYTHON, unichr
import datetime
from decimal import Decimal
import re
import time
from . import FIELD_TYPE, FLAG
from .charset import charset_by_id, charset_to_encoding
def escape_item(val, charset, mapping=None):
if mapping is None:
mapping = encoders
encoder = mapping.get(type(val))
# Fallback to default when no encoder found
if not encoder:
try:
encoder = mapping[text_type]
except KeyError:
raise TypeError("no default type converter defined")
if encoder in (escape_dict, escape_sequence):
val = encoder(val, charset, mapping)
else:
val = encoder(val, mapping)
return val
def escape_dict(val, charset, mapping=None):
n = {}
for k, v in val.items():
quoted = escape_item(v, charset, mapping)
n[k] = quoted
return n
def escape_sequence(val, charset, mapping=None):
n = []
for item in val:
quoted = escape_item(item, charset, mapping)
n.append(quoted)
return "(" + ",".join(n) + ")"
def escape_set(val, charset, mapping=None):
return ','.join([escape_item(x, charset, mapping) for x in val])
def escape_bool(value, mapping=None):
return str(int(value))
def escape_object(value, mapping=None):
return str(value)
def escape_int(value, mapping=None):
return str(value)
def escape_float(value, mapping=None):
return ('%.15g' % value)
_escape_table = [unichr(x) for x in range(128)]
_escape_table[0] = u'\\0'
_escape_table[ord('\\')] = u'\\\\'
_escape_table[ord('\n')] = u'\\n'
_escape_table[ord('\r')] = u'\\r'
_escape_table[ord('\032')] = u'\\Z'
_escape_table[ord('"')] = u'\\"'
_escape_table[ord("'")] = u"\\'"
def _escape_unicode(value, mapping=None):
"""escapes *value* without adding quote.
Value should be unicode
"""
return value.translate(_escape_table)
if PY2:
def escape_string(value, mapping=None):
"""escape_string escapes *value* but not surround it with quotes.
Value should be bytes or unicode.
"""
if isinstance(value, unicode):
return _escape_unicode(value)
assert isinstance(value, (bytes, bytearray))
value = value.replace('\\', '\\\\')
value = value.replace('\0', '\\0')
value = value.replace('\n', '\\n')
value = value.replace('\r', '\\r')
value = value.replace('\032', '\\Z')
value = value.replace("'", "\\'")
value = value.replace('"', '\\"')
return value
def escape_bytes_prefixed(value, mapping=None):
assert isinstance(value, (bytes, bytearray))
return b"_binary'%s'" % escape_string(value)
def escape_bytes(value, mapping=None):
assert isinstance(value, (bytes, bytearray))
return b"'%s'" % escape_string(value)
else:
escape_string = _escape_unicode
# On Python ~3.5, str.decode('ascii', 'surrogateescape') is slow.
# (fixed in Python 3.6, http://bugs.python.org/issue24870)
# Workaround is str.decode('latin1') then translate 0x80-0xff into 0udc80-0udcff.
# We can escape special chars and surrogateescape at once.
_escape_bytes_table = _escape_table + [chr(i) for i in range(0xdc80, 0xdd00)]
def escape_bytes_prefixed(value, mapping=None):
return "_binary'%s'" % value.decode('latin1').translate(_escape_bytes_table)
def escape_bytes(value, mapping=None):
return "'%s'" % value.decode('latin1').translate(_escape_bytes_table)
def escape_unicode(value, mapping=None):
return u"'%s'" % _escape_unicode(value)
def escape_str(value, mapping=None):
return "'%s'" % escape_string(str(value), mapping)
def escape_None(value, mapping=None):
return 'NULL'
def escape_timedelta(obj, mapping=None):
seconds = int(obj.seconds) % 60
minutes = int(obj.seconds // 60) % 60
hours = int(obj.seconds // 3600) % 24 + int(obj.days) * 24
if obj.microseconds:
fmt = "'{0:02d}:{1:02d}:{2:02d}.{3:06d}'"
else:
fmt = "'{0:02d}:{1:02d}:{2:02d}'"
return fmt.format(hours, minutes, seconds, obj.microseconds)
def escape_time(obj, mapping=None):
if obj.microsecond:
fmt = "'{0.hour:02}:{0.minute:02}:{0.second:02}.{0.microsecond:06}'"
else:
fmt = "'{0.hour:02}:{0.minute:02}:{0.second:02}'"
return fmt.format(obj)
def escape_datetime(obj, mapping=None):
if obj.microsecond:
fmt = "'{0.year:04}-{0.month:02}-{0.day:02} {0.hour:02}:{0.minute:02}:{0.second:02}.{0.microsecond:06}'"
else:
fmt = "'{0.year:04}-{0.month:02}-{0.day:02} {0.hour:02}:{0.minute:02}:{0.second:02}'"
return fmt.format(obj)
def escape_date(obj, mapping=None):
fmt = "'{0.year:04}-{0.month:02}-{0.day:02}'"
return fmt.format(obj)
def escape_struct_time(obj, mapping=None):
return escape_datetime(datetime.datetime(*obj[:6]))
def _convert_second_fraction(s):
if not s:
return 0
# Pad zeros to ensure the fraction length in microseconds
s = s.ljust(6, '0')
return int(s[:6])
DATETIME_RE = re.compile(r"(\d{1,4})-(\d{1,2})-(\d{1,2})[T ](\d{1,2}):(\d{1,2}):(\d{1,2})(?:.(\d{1,6}))?")
def convert_datetime(obj):
"""Returns a DATETIME or TIMESTAMP column value as a datetime object:
>>> datetime_or_None('2007-02-25 23:06:20')
datetime.datetime(2007, 2, 25, 23, 6, 20)
>>> datetime_or_None('2007-02-25T23:06:20')
datetime.datetime(2007, 2, 25, 23, 6, 20)
Illegal values are returned as None:
>>> datetime_or_None('2007-02-31T23:06:20') is None
True
>>> datetime_or_None('0000-00-00 00:00:00') is None
True
"""
if not PY2 and isinstance(obj, (bytes, bytearray)):
obj = obj.decode('ascii')
m = DATETIME_RE.match(obj)
if not m:
return convert_date(obj)
try:
groups = list(m.groups())
groups[-1] = _convert_second_fraction(groups[-1])
return datetime.datetime(*[ int(x) for x in groups ])
except ValueError:
return convert_date(obj)
TIMEDELTA_RE = re.compile(r"(-)?(\d{1,3}):(\d{1,2}):(\d{1,2})(?:.(\d{1,6}))?")
def convert_timedelta(obj):
"""Returns a TIME column as a timedelta object:
>>> timedelta_or_None('25:06:17')
datetime.timedelta(1, 3977)
>>> timedelta_or_None('-25:06:17')
datetime.timedelta(-2, 83177)
Illegal values are returned as None:
>>> timedelta_or_None('random crap') is None
True
Note that MySQL always returns TIME columns as (+|-)HH:MM:SS, but
can accept values as (+|-)DD HH:MM:SS. The latter format will not
be parsed correctly by this function.
"""
if not PY2 and isinstance(obj, (bytes, bytearray)):
obj = obj.decode('ascii')
m = TIMEDELTA_RE.match(obj)
if not m:
return obj
try:
groups = list(m.groups())
groups[-1] = _convert_second_fraction(groups[-1])
negate = -1 if groups[0] else 1
hours, minutes, seconds, microseconds = groups[1:]
tdelta = datetime.timedelta(
hours = int(hours),
minutes = int(minutes),
seconds = int(seconds),
microseconds = int(microseconds)
) * negate
return tdelta
except ValueError:
return obj
TIME_RE = re.compile(r"(\d{1,2}):(\d{1,2}):(\d{1,2})(?:.(\d{1,6}))?")
def convert_time(obj):
"""Returns a TIME column as a time object:
>>> time_or_None('15:06:17')
datetime.time(15, 6, 17)
Illegal values are returned as None:
>>> time_or_None('-25:06:17') is None
True
>>> time_or_None('random crap') is None
True
Note that MySQL always returns TIME columns as (+|-)HH:MM:SS, but
can accept values as (+|-)DD HH:MM:SS. The latter format will not
be parsed correctly by this function.
Also note that MySQL's TIME column corresponds more closely to
Python's timedelta and not time. However if you want TIME columns
to be treated as time-of-day and not a time offset, then you can
use set this function as the converter for FIELD_TYPE.TIME.
"""
if not PY2 and isinstance(obj, (bytes, bytearray)):
obj = obj.decode('ascii')
m = TIME_RE.match(obj)
if not m:
return obj
try:
groups = list(m.groups())
groups[-1] = _convert_second_fraction(groups[-1])
hours, minutes, seconds, microseconds = groups
return datetime.time(hour=int(hours), minute=int(minutes),
second=int(seconds), microsecond=int(microseconds))
except ValueError:
return obj
def convert_date(obj):
"""Returns a DATE column as a date object:
>>> date_or_None('2007-02-26')
datetime.date(2007, 2, 26)
Illegal values are returned as None:
>>> date_or_None('2007-02-31') is None
True
>>> date_or_None('0000-00-00') is None
True
"""
if not PY2 and isinstance(obj, (bytes, bytearray)):
obj = obj.decode('ascii')
try:
return datetime.date(*[ int(x) for x in obj.split('-', 2) ])
except ValueError:
return obj
def convert_mysql_timestamp(timestamp):
"""Convert a MySQL TIMESTAMP to a Timestamp object.
MySQL >= 4.1 returns TIMESTAMP in the same format as DATETIME:
>>> mysql_timestamp_converter('2007-02-25 22:32:17')
datetime.datetime(2007, 2, 25, 22, 32, 17)
MySQL < 4.1 uses a big string of numbers:
>>> mysql_timestamp_converter('20070225223217')
datetime.datetime(2007, 2, 25, 22, 32, 17)
Illegal values are returned as None:
>>> mysql_timestamp_converter('2007-02-31 22:32:17') is None
True
>>> mysql_timestamp_converter('00000000000000') is None
True
"""
if not PY2 and isinstance(timestamp, (bytes, bytearray)):
timestamp = timestamp.decode('ascii')
if timestamp[4] == '-':
return convert_datetime(timestamp)
timestamp += "0"*(14-len(timestamp)) # padding
year, month, day, hour, minute, second = \
int(timestamp[:4]), int(timestamp[4:6]), int(timestamp[6:8]), \
int(timestamp[8:10]), int(timestamp[10:12]), int(timestamp[12:14])
try:
return datetime.datetime(year, month, day, hour, minute, second)
except ValueError:
return timestamp
def convert_set(s):
if isinstance(s, (bytes, bytearray)):
return set(s.split(b","))
return set(s.split(","))
def through(x):
return x
#def convert_bit(b):
# b = "\x00" * (8 - len(b)) + b # pad w/ zeroes
# return struct.unpack(">Q", b)[0]
#
# the snippet above is right, but MySQLdb doesn't process bits,
# so we shouldn't either
convert_bit = through
def convert_characters(connection, field, data):
field_charset = charset_by_id(field.charsetnr).name
encoding = charset_to_encoding(field_charset)
if field.flags & FLAG.SET:
return convert_set(data.decode(encoding))
if field.flags & FLAG.BINARY:
return data
if connection.use_unicode:
data = data.decode(encoding)
elif connection.charset != field_charset:
data = data.decode(encoding)
data = data.encode(connection.encoding)
return data
encoders = {
bool: escape_bool,
int: escape_int,
long_type: escape_int,
float: escape_float,
str: escape_str,
text_type: escape_unicode,
tuple: escape_sequence,
list: escape_sequence,
set: escape_sequence,
frozenset: escape_sequence,
dict: escape_dict,
type(None): escape_None,
datetime.date: escape_date,
datetime.datetime: escape_datetime,
datetime.timedelta: escape_timedelta,
datetime.time: escape_time,
time.struct_time: escape_struct_time,
Decimal: escape_object,
}
if not PY2 or JYTHON or IRONPYTHON:
encoders[bytes] = escape_bytes
decoders = {
FIELD_TYPE.BIT: convert_bit,
FIELD_TYPE.TINY: int,
FIELD_TYPE.SHORT: int,
FIELD_TYPE.LONG: int,
FIELD_TYPE.FLOAT: float,
FIELD_TYPE.DOUBLE: float,
FIELD_TYPE.LONGLONG: int,
FIELD_TYPE.INT24: int,
FIELD_TYPE.YEAR: int,
FIELD_TYPE.TIMESTAMP: convert_mysql_timestamp,
FIELD_TYPE.DATETIME: convert_datetime,
FIELD_TYPE.TIME: convert_timedelta,
FIELD_TYPE.DATE: convert_date,
FIELD_TYPE.SET: convert_set,
FIELD_TYPE.BLOB: through,
FIELD_TYPE.TINY_BLOB: through,
FIELD_TYPE.MEDIUM_BLOB: through,
FIELD_TYPE.LONG_BLOB: through,
FIELD_TYPE.STRING: through,
FIELD_TYPE.VAR_STRING: through,
FIELD_TYPE.VARCHAR: through,
FIELD_TYPE.DECIMAL: Decimal,
FIELD_TYPE.NEWDECIMAL: Decimal,
}
# for MySQLdb compatibility
conversions = encoders.copy()
conversions.update(decoders)
Thing2Literal = escape_str | ytp1 | /ytp1-6.3.12-cp36-cp36m-win_amd64.whl/pymysql/converters.py | converters.py |
from __future__ import print_function, absolute_import
from functools import partial
import re
import warnings
from ._compat import range_type, text_type, PY2
from . import err
#: Regular expression for :meth:`Cursor.executemany`.
#: executemany only suports simple bulk insert.
#: You can use it to load large dataset.
RE_INSERT_VALUES = re.compile(
r"\s*((?:INSERT|REPLACE)\b.+\bVALUES?\s*)" +
r"(\(\s*(?:%s|%\(.+\)s)\s*(?:,\s*(?:%s|%\(.+\)s)\s*)*\))" +
r"(\s*(?:ON DUPLICATE.*)?);?\s*\Z",
re.IGNORECASE | re.DOTALL)
class Cursor(object):
"""
This is the object you use to interact with the database.
Do not create an instance of a Cursor yourself. Call
connections.Connection.cursor().
See `Cursor <https://www.python.org/dev/peps/pep-0249/#cursor-objects>`_ in
the specification.
"""
#: Max statement size which :meth:`executemany` generates.
#:
#: Max size of allowed statement is max_allowed_packet - packet_header_size.
#: Default value of max_allowed_packet is 1048576.
max_stmt_length = 1024000
_defer_warnings = False
def __init__(self, connection):
self.connection = connection
self.description = None
self.rownumber = 0
self.rowcount = -1
self.arraysize = 1
self._executed = None
self._result = None
self._rows = None
self._warnings_handled = False
def close(self):
"""
Closing a cursor just exhausts all remaining data.
"""
conn = self.connection
if conn is None:
return
try:
while self.nextset():
pass
finally:
self.connection = None
def __enter__(self):
return self
def __exit__(self, *exc_info):
del exc_info
self.close()
def _get_db(self):
if not self.connection:
raise err.ProgrammingError("Cursor closed")
return self.connection
def _check_executed(self):
if not self._executed:
raise err.ProgrammingError("execute() first")
def _conv_row(self, row):
return row
def setinputsizes(self, *args):
"""Does nothing, required by DB API."""
def setoutputsizes(self, *args):
"""Does nothing, required by DB API."""
def _nextset(self, unbuffered=False):
"""Get the next query set"""
conn = self._get_db()
current_result = self._result
# for unbuffered queries warnings are only available once whole result has been read
if unbuffered:
self._show_warnings()
if current_result is None or current_result is not conn._result:
return None
if not current_result.has_next:
return None
self._result = None
self._clear_result()
conn.next_result(unbuffered=unbuffered)
self._do_get_result()
return True
def nextset(self):
return self._nextset(False)
def _ensure_bytes(self, x, encoding=None):
if isinstance(x, text_type):
x = x.encode(encoding)
elif isinstance(x, (tuple, list)):
x = type(x)(self._ensure_bytes(v, encoding=encoding) for v in x)
return x
def _escape_args(self, args, conn):
ensure_bytes = partial(self._ensure_bytes, encoding=conn.encoding)
if isinstance(args, (tuple, list)):
if PY2:
args = tuple(map(ensure_bytes, args))
return tuple(conn.literal(arg) for arg in args)
elif isinstance(args, dict):
if PY2:
args = dict((ensure_bytes(key), ensure_bytes(val)) for
(key, val) in args.items())
return dict((key, conn.literal(val)) for (key, val) in args.items())
else:
# If it's not a dictionary let's try escaping it anyways.
# Worst case it will throw a Value error
if PY2:
args = ensure_bytes(args)
return conn.escape(args)
def mogrify(self, query, args=None):
"""
Returns the exact string that is sent to the database by calling the
execute() method.
This method follows the extension to the DB API 2.0 followed by Psycopg.
"""
conn = self._get_db()
if PY2: # Use bytes on Python 2 always
query = self._ensure_bytes(query, encoding=conn.encoding)
if args is not None:
query = query % self._escape_args(args, conn)
return query
def execute(self, query, args=None):
"""Execute a query
:param str query: Query to execute.
:param args: parameters used with query. (optional)
:type args: tuple, list or dict
:return: Number of affected rows
:rtype: int
If args is a list or tuple, %s can be used as a placeholder in the query.
If args is a dict, %(name)s can be used as a placeholder in the query.
"""
while self.nextset():
pass
query = self.mogrify(query, args)
result = self._query(query)
self._executed = query
return result
def executemany(self, query, args):
# type: (str, list) -> int
"""Run several data against one query
:param query: query to execute on server
:param args: Sequence of sequences or mappings. It is used as parameter.
:return: Number of rows affected, if any.
This method improves performance on multiple-row INSERT and
REPLACE. Otherwise it is equivalent to looping over args with
execute().
"""
if not args:
return
m = RE_INSERT_VALUES.match(query)
if m:
q_prefix = m.group(1) % ()
q_values = m.group(2).rstrip()
q_postfix = m.group(3) or ''
assert q_values[0] == '(' and q_values[-1] == ')'
return self._do_execute_many(q_prefix, q_values, q_postfix, args,
self.max_stmt_length,
self._get_db().encoding)
self.rowcount = sum(self.execute(query, arg) for arg in args)
return self.rowcount
def _do_execute_many(self, prefix, values, postfix, args, max_stmt_length, encoding):
conn = self._get_db()
escape = self._escape_args
if isinstance(prefix, text_type):
prefix = prefix.encode(encoding)
if PY2 and isinstance(values, text_type):
values = values.encode(encoding)
if isinstance(postfix, text_type):
postfix = postfix.encode(encoding)
sql = bytearray(prefix)
args = iter(args)
v = values % escape(next(args), conn)
if isinstance(v, text_type):
if PY2:
v = v.encode(encoding)
else:
v = v.encode(encoding, 'surrogateescape')
sql += v
rows = 0
for arg in args:
v = values % escape(arg, conn)
if isinstance(v, text_type):
if PY2:
v = v.encode(encoding)
else:
v = v.encode(encoding, 'surrogateescape')
if len(sql) + len(v) + len(postfix) + 1 > max_stmt_length:
rows += self.execute(sql + postfix)
sql = bytearray(prefix)
else:
sql += b','
sql += v
rows += self.execute(sql + postfix)
self.rowcount = rows
return rows
def callproc(self, procname, args=()):
"""Execute stored procedure procname with args
procname -- string, name of procedure to execute on server
args -- Sequence of parameters to use with procedure
Returns the original args.
Compatibility warning: PEP-249 specifies that any modified
parameters must be returned. This is currently impossible
as they are only available by storing them in a server
variable and then retrieved by a query. Since stored
procedures return zero or more result sets, there is no
reliable way to get at OUT or INOUT parameters via callproc.
The server variables are named @_procname_n, where procname
is the parameter above and n is the position of the parameter
(from zero). Once all result sets generated by the procedure
have been fetched, you can issue a SELECT @_procname_0, ...
query using .execute() to get any OUT or INOUT values.
Compatibility warning: The act of calling a stored procedure
itself creates an empty result set. This appears after any
result sets generated by the procedure. This is non-standard
behavior with respect to the DB-API. Be sure to use nextset()
to advance through all result sets; otherwise you may get
disconnected.
"""
conn = self._get_db()
if args:
fmt = '@_{0}_%d=%s'.format(procname)
self._query('SET %s' % ','.join(fmt % (index, conn.escape(arg))
for index, arg in enumerate(args)))
self.nextset()
q = "CALL %s(%s)" % (procname,
','.join(['@_%s_%d' % (procname, i)
for i in range_type(len(args))]))
self._query(q)
self._executed = q
return args
def fetchone(self):
"""Fetch the next row"""
self._check_executed()
if self._rows is None or self.rownumber >= len(self._rows):
return None
result = self._rows[self.rownumber]
self.rownumber += 1
return result
def fetchmany(self, size=None):
"""Fetch several rows"""
self._check_executed()
if self._rows is None:
return ()
end = self.rownumber + (size or self.arraysize)
result = self._rows[self.rownumber:end]
self.rownumber = min(end, len(self._rows))
return result
def fetchall(self):
"""Fetch all the rows"""
self._check_executed()
if self._rows is None:
return ()
if self.rownumber:
result = self._rows[self.rownumber:]
else:
result = self._rows
self.rownumber = len(self._rows)
return result
def scroll(self, value, mode='relative'):
self._check_executed()
if mode == 'relative':
r = self.rownumber + value
elif mode == 'absolute':
r = value
else:
raise err.ProgrammingError("unknown scroll mode %s" % mode)
if not (0 <= r < len(self._rows)):
raise IndexError("out of range")
self.rownumber = r
def _query(self, q):
conn = self._get_db()
self._last_executed = q
self._clear_result()
conn.query(q)
self._do_get_result()
return self.rowcount
def _clear_result(self):
self.rownumber = 0
self._result = None
self.rowcount = 0
self.description = None
self.lastrowid = None
self._rows = None
def _do_get_result(self):
conn = self._get_db()
self._result = result = conn._result
self.rowcount = result.affected_rows
self.description = result.description
self.lastrowid = result.insert_id
self._rows = result.rows
self._warnings_handled = False
if not self._defer_warnings:
self._show_warnings()
def _show_warnings(self):
if self._warnings_handled:
return
self._warnings_handled = True
if self._result and (self._result.has_next or not self._result.warning_count):
return
ws = self._get_db().show_warnings()
if ws is None:
return
for w in ws:
msg = w[-1]
if PY2:
if isinstance(msg, unicode):
msg = msg.encode('utf-8', 'replace')
warnings.warn(err.Warning(*w[1:3]), stacklevel=4)
def __iter__(self):
return iter(self.fetchone, None)
Warning = err.Warning
Error = err.Error
InterfaceError = err.InterfaceError
DatabaseError = err.DatabaseError
DataError = err.DataError
OperationalError = err.OperationalError
IntegrityError = err.IntegrityError
InternalError = err.InternalError
ProgrammingError = err.ProgrammingError
NotSupportedError = err.NotSupportedError
class DictCursorMixin(object):
# You can override this to use OrderedDict or other dict-like types.
dict_type = dict
def _do_get_result(self):
super(DictCursorMixin, self)._do_get_result()
fields = []
if self.description:
for f in self._result.fields:
name = f.name
if name in fields:
name = f.table_name + '.' + name
fields.append(name)
self._fields = fields
if fields and self._rows:
self._rows = [self._conv_row(r) for r in self._rows]
def _conv_row(self, row):
if row is None:
return None
return self.dict_type(zip(self._fields, row))
class DictCursor(DictCursorMixin, Cursor):
"""A cursor which returns results as a dictionary"""
class SSCursor(Cursor):
"""
Unbuffered Cursor, mainly useful for queries that return a lot of data,
or for connections to remote servers over a slow network.
Instead of copying every row of data into a buffer, this will fetch
rows as needed. The upside of this is the client uses much less memory,
and rows are returned much faster when traveling over a slow network
or if the result set is very big.
There are limitations, though. The MySQL protocol doesn't support
returning the total number of rows, so the only way to tell how many rows
there are is to iterate over every row returned. Also, it currently isn't
possible to scroll backwards, as only the current row is held in memory.
"""
_defer_warnings = True
def _conv_row(self, row):
return row
def close(self):
conn = self.connection
if conn is None:
return
if self._result is not None and self._result is conn._result:
self._result._finish_unbuffered_query()
try:
while self.nextset():
pass
finally:
self.connection = None
__del__ = close
def _query(self, q):
conn = self._get_db()
self._last_executed = q
self._clear_result()
conn.query(q, unbuffered=True)
self._do_get_result()
return self.rowcount
def nextset(self):
return self._nextset(unbuffered=True)
def read_next(self):
"""Read next row"""
return self._conv_row(self._result._read_rowdata_packet_unbuffered())
def fetchone(self):
"""Fetch next row"""
self._check_executed()
row = self.read_next()
if row is None:
self._show_warnings()
return None
self.rownumber += 1
return row
def fetchall(self):
"""
Fetch all, as per MySQLdb. Pretty useless for large queries, as
it is buffered. See fetchall_unbuffered(), if you want an unbuffered
generator version of this method.
"""
return list(self.fetchall_unbuffered())
def fetchall_unbuffered(self):
"""
Fetch all, implemented as a generator, which isn't to standard,
however, it doesn't make sense to return everything in a list, as that
would use ridiculous memory for large result sets.
"""
return iter(self.fetchone, None)
def __iter__(self):
return self.fetchall_unbuffered()
def fetchmany(self, size=None):
"""Fetch many"""
self._check_executed()
if size is None:
size = self.arraysize
rows = []
for i in range_type(size):
row = self.read_next()
if row is None:
self._show_warnings()
break
rows.append(row)
self.rownumber += 1
return rows
def scroll(self, value, mode='relative'):
self._check_executed()
if mode == 'relative':
if value < 0:
raise err.NotSupportedError(
"Backwards scrolling not supported by this cursor")
for _ in range_type(value):
self.read_next()
self.rownumber += value
elif mode == 'absolute':
if value < self.rownumber:
raise err.NotSupportedError(
"Backwards scrolling not supported by this cursor")
end = value - self.rownumber
for _ in range_type(end):
self.read_next()
self.rownumber = value
else:
raise err.ProgrammingError("unknown scroll mode %s" % mode)
class SSDictCursor(DictCursorMixin, SSCursor):
"""An unbuffered cursor, which returns results as a dictionary""" | ytp1 | /ytp1-6.3.12-cp36-cp36m-win_amd64.whl/pymysql/cursors.py | cursors.py |
MBLENGTH = {
8:1,
33:3,
88:2,
91:2
}
class Charset(object):
def __init__(self, id, name, collation, is_default):
self.id, self.name, self.collation = id, name, collation
self.is_default = is_default == 'Yes'
def __repr__(self):
return "Charset(id=%s, name=%r, collation=%r)" % (
self.id, self.name, self.collation)
@property
def encoding(self):
name = self.name
if name == 'utf8mb4':
return 'utf8'
return name
@property
def is_binary(self):
return self.id == 63
class Charsets:
def __init__(self):
self._by_id = {}
def add(self, c):
self._by_id[c.id] = c
def by_id(self, id):
return self._by_id[id]
def by_name(self, name):
name = name.lower()
for c in self._by_id.values():
if c.name == name and c.is_default:
return c
_charsets = Charsets()
"""
Generated with:
mysql -N -s -e "select id, character_set_name, collation_name, is_default
from information_schema.collations order by id;" | python -c "import sys
for l in sys.stdin.readlines():
id, name, collation, is_default = l.split(chr(9))
print '_charsets.add(Charset(%s, \'%s\', \'%s\', \'%s\'))' \
% (id, name, collation, is_default.strip())
"
"""
_charsets.add(Charset(1, 'big5', 'big5_chinese_ci', 'Yes'))
_charsets.add(Charset(2, 'latin2', 'latin2_czech_cs', ''))
_charsets.add(Charset(3, 'dec8', 'dec8_swedish_ci', 'Yes'))
_charsets.add(Charset(4, 'cp850', 'cp850_general_ci', 'Yes'))
_charsets.add(Charset(5, 'latin1', 'latin1_german1_ci', ''))
_charsets.add(Charset(6, 'hp8', 'hp8_english_ci', 'Yes'))
_charsets.add(Charset(7, 'koi8r', 'koi8r_general_ci', 'Yes'))
_charsets.add(Charset(8, 'latin1', 'latin1_swedish_ci', 'Yes'))
_charsets.add(Charset(9, 'latin2', 'latin2_general_ci', 'Yes'))
_charsets.add(Charset(10, 'swe7', 'swe7_swedish_ci', 'Yes'))
_charsets.add(Charset(11, 'ascii', 'ascii_general_ci', 'Yes'))
_charsets.add(Charset(12, 'ujis', 'ujis_japanese_ci', 'Yes'))
_charsets.add(Charset(13, 'sjis', 'sjis_japanese_ci', 'Yes'))
_charsets.add(Charset(14, 'cp1251', 'cp1251_bulgarian_ci', ''))
_charsets.add(Charset(15, 'latin1', 'latin1_danish_ci', ''))
_charsets.add(Charset(16, 'hebrew', 'hebrew_general_ci', 'Yes'))
_charsets.add(Charset(18, 'tis620', 'tis620_thai_ci', 'Yes'))
_charsets.add(Charset(19, 'euckr', 'euckr_korean_ci', 'Yes'))
_charsets.add(Charset(20, 'latin7', 'latin7_estonian_cs', ''))
_charsets.add(Charset(21, 'latin2', 'latin2_hungarian_ci', ''))
_charsets.add(Charset(22, 'koi8u', 'koi8u_general_ci', 'Yes'))
_charsets.add(Charset(23, 'cp1251', 'cp1251_ukrainian_ci', ''))
_charsets.add(Charset(24, 'gb2312', 'gb2312_chinese_ci', 'Yes'))
_charsets.add(Charset(25, 'greek', 'greek_general_ci', 'Yes'))
_charsets.add(Charset(26, 'cp1250', 'cp1250_general_ci', 'Yes'))
_charsets.add(Charset(27, 'latin2', 'latin2_croatian_ci', ''))
_charsets.add(Charset(28, 'gbk', 'gbk_chinese_ci', 'Yes'))
_charsets.add(Charset(29, 'cp1257', 'cp1257_lithuanian_ci', ''))
_charsets.add(Charset(30, 'latin5', 'latin5_turkish_ci', 'Yes'))
_charsets.add(Charset(31, 'latin1', 'latin1_german2_ci', ''))
_charsets.add(Charset(32, 'armscii8', 'armscii8_general_ci', 'Yes'))
_charsets.add(Charset(33, 'utf8', 'utf8_general_ci', 'Yes'))
_charsets.add(Charset(34, 'cp1250', 'cp1250_czech_cs', ''))
_charsets.add(Charset(35, 'ucs2', 'ucs2_general_ci', 'Yes'))
_charsets.add(Charset(36, 'cp866', 'cp866_general_ci', 'Yes'))
_charsets.add(Charset(37, 'keybcs2', 'keybcs2_general_ci', 'Yes'))
_charsets.add(Charset(38, 'macce', 'macce_general_ci', 'Yes'))
_charsets.add(Charset(39, 'macroman', 'macroman_general_ci', 'Yes'))
_charsets.add(Charset(40, 'cp852', 'cp852_general_ci', 'Yes'))
_charsets.add(Charset(41, 'latin7', 'latin7_general_ci', 'Yes'))
_charsets.add(Charset(42, 'latin7', 'latin7_general_cs', ''))
_charsets.add(Charset(43, 'macce', 'macce_bin', ''))
_charsets.add(Charset(44, 'cp1250', 'cp1250_croatian_ci', ''))
_charsets.add(Charset(45, 'utf8mb4', 'utf8mb4_general_ci', 'Yes'))
_charsets.add(Charset(46, 'utf8mb4', 'utf8mb4_bin', ''))
_charsets.add(Charset(47, 'latin1', 'latin1_bin', ''))
_charsets.add(Charset(48, 'latin1', 'latin1_general_ci', ''))
_charsets.add(Charset(49, 'latin1', 'latin1_general_cs', ''))
_charsets.add(Charset(50, 'cp1251', 'cp1251_bin', ''))
_charsets.add(Charset(51, 'cp1251', 'cp1251_general_ci', 'Yes'))
_charsets.add(Charset(52, 'cp1251', 'cp1251_general_cs', ''))
_charsets.add(Charset(53, 'macroman', 'macroman_bin', ''))
_charsets.add(Charset(54, 'utf16', 'utf16_general_ci', 'Yes'))
_charsets.add(Charset(55, 'utf16', 'utf16_bin', ''))
_charsets.add(Charset(57, 'cp1256', 'cp1256_general_ci', 'Yes'))
_charsets.add(Charset(58, 'cp1257', 'cp1257_bin', ''))
_charsets.add(Charset(59, 'cp1257', 'cp1257_general_ci', 'Yes'))
_charsets.add(Charset(60, 'utf32', 'utf32_general_ci', 'Yes'))
_charsets.add(Charset(61, 'utf32', 'utf32_bin', ''))
_charsets.add(Charset(63, 'binary', 'binary', 'Yes'))
_charsets.add(Charset(64, 'armscii8', 'armscii8_bin', ''))
_charsets.add(Charset(65, 'ascii', 'ascii_bin', ''))
_charsets.add(Charset(66, 'cp1250', 'cp1250_bin', ''))
_charsets.add(Charset(67, 'cp1256', 'cp1256_bin', ''))
_charsets.add(Charset(68, 'cp866', 'cp866_bin', ''))
_charsets.add(Charset(69, 'dec8', 'dec8_bin', ''))
_charsets.add(Charset(70, 'greek', 'greek_bin', ''))
_charsets.add(Charset(71, 'hebrew', 'hebrew_bin', ''))
_charsets.add(Charset(72, 'hp8', 'hp8_bin', ''))
_charsets.add(Charset(73, 'keybcs2', 'keybcs2_bin', ''))
_charsets.add(Charset(74, 'koi8r', 'koi8r_bin', ''))
_charsets.add(Charset(75, 'koi8u', 'koi8u_bin', ''))
_charsets.add(Charset(77, 'latin2', 'latin2_bin', ''))
_charsets.add(Charset(78, 'latin5', 'latin5_bin', ''))
_charsets.add(Charset(79, 'latin7', 'latin7_bin', ''))
_charsets.add(Charset(80, 'cp850', 'cp850_bin', ''))
_charsets.add(Charset(81, 'cp852', 'cp852_bin', ''))
_charsets.add(Charset(82, 'swe7', 'swe7_bin', ''))
_charsets.add(Charset(83, 'utf8', 'utf8_bin', ''))
_charsets.add(Charset(84, 'big5', 'big5_bin', ''))
_charsets.add(Charset(85, 'euckr', 'euckr_bin', ''))
_charsets.add(Charset(86, 'gb2312', 'gb2312_bin', ''))
_charsets.add(Charset(87, 'gbk', 'gbk_bin', ''))
_charsets.add(Charset(88, 'sjis', 'sjis_bin', ''))
_charsets.add(Charset(89, 'tis620', 'tis620_bin', ''))
_charsets.add(Charset(90, 'ucs2', 'ucs2_bin', ''))
_charsets.add(Charset(91, 'ujis', 'ujis_bin', ''))
_charsets.add(Charset(92, 'geostd8', 'geostd8_general_ci', 'Yes'))
_charsets.add(Charset(93, 'geostd8', 'geostd8_bin', ''))
_charsets.add(Charset(94, 'latin1', 'latin1_spanish_ci', ''))
_charsets.add(Charset(95, 'cp932', 'cp932_japanese_ci', 'Yes'))
_charsets.add(Charset(96, 'cp932', 'cp932_bin', ''))
_charsets.add(Charset(97, 'eucjpms', 'eucjpms_japanese_ci', 'Yes'))
_charsets.add(Charset(98, 'eucjpms', 'eucjpms_bin', ''))
_charsets.add(Charset(99, 'cp1250', 'cp1250_polish_ci', ''))
_charsets.add(Charset(101, 'utf16', 'utf16_unicode_ci', ''))
_charsets.add(Charset(102, 'utf16', 'utf16_icelandic_ci', ''))
_charsets.add(Charset(103, 'utf16', 'utf16_latvian_ci', ''))
_charsets.add(Charset(104, 'utf16', 'utf16_romanian_ci', ''))
_charsets.add(Charset(105, 'utf16', 'utf16_slovenian_ci', ''))
_charsets.add(Charset(106, 'utf16', 'utf16_polish_ci', ''))
_charsets.add(Charset(107, 'utf16', 'utf16_estonian_ci', ''))
_charsets.add(Charset(108, 'utf16', 'utf16_spanish_ci', ''))
_charsets.add(Charset(109, 'utf16', 'utf16_swedish_ci', ''))
_charsets.add(Charset(110, 'utf16', 'utf16_turkish_ci', ''))
_charsets.add(Charset(111, 'utf16', 'utf16_czech_ci', ''))
_charsets.add(Charset(112, 'utf16', 'utf16_danish_ci', ''))
_charsets.add(Charset(113, 'utf16', 'utf16_lithuanian_ci', ''))
_charsets.add(Charset(114, 'utf16', 'utf16_slovak_ci', ''))
_charsets.add(Charset(115, 'utf16', 'utf16_spanish2_ci', ''))
_charsets.add(Charset(116, 'utf16', 'utf16_roman_ci', ''))
_charsets.add(Charset(117, 'utf16', 'utf16_persian_ci', ''))
_charsets.add(Charset(118, 'utf16', 'utf16_esperanto_ci', ''))
_charsets.add(Charset(119, 'utf16', 'utf16_hungarian_ci', ''))
_charsets.add(Charset(120, 'utf16', 'utf16_sinhala_ci', ''))
_charsets.add(Charset(128, 'ucs2', 'ucs2_unicode_ci', ''))
_charsets.add(Charset(129, 'ucs2', 'ucs2_icelandic_ci', ''))
_charsets.add(Charset(130, 'ucs2', 'ucs2_latvian_ci', ''))
_charsets.add(Charset(131, 'ucs2', 'ucs2_romanian_ci', ''))
_charsets.add(Charset(132, 'ucs2', 'ucs2_slovenian_ci', ''))
_charsets.add(Charset(133, 'ucs2', 'ucs2_polish_ci', ''))
_charsets.add(Charset(134, 'ucs2', 'ucs2_estonian_ci', ''))
_charsets.add(Charset(135, 'ucs2', 'ucs2_spanish_ci', ''))
_charsets.add(Charset(136, 'ucs2', 'ucs2_swedish_ci', ''))
_charsets.add(Charset(137, 'ucs2', 'ucs2_turkish_ci', ''))
_charsets.add(Charset(138, 'ucs2', 'ucs2_czech_ci', ''))
_charsets.add(Charset(139, 'ucs2', 'ucs2_danish_ci', ''))
_charsets.add(Charset(140, 'ucs2', 'ucs2_lithuanian_ci', ''))
_charsets.add(Charset(141, 'ucs2', 'ucs2_slovak_ci', ''))
_charsets.add(Charset(142, 'ucs2', 'ucs2_spanish2_ci', ''))
_charsets.add(Charset(143, 'ucs2', 'ucs2_roman_ci', ''))
_charsets.add(Charset(144, 'ucs2', 'ucs2_persian_ci', ''))
_charsets.add(Charset(145, 'ucs2', 'ucs2_esperanto_ci', ''))
_charsets.add(Charset(146, 'ucs2', 'ucs2_hungarian_ci', ''))
_charsets.add(Charset(147, 'ucs2', 'ucs2_sinhala_ci', ''))
_charsets.add(Charset(159, 'ucs2', 'ucs2_general_mysql500_ci', ''))
_charsets.add(Charset(160, 'utf32', 'utf32_unicode_ci', ''))
_charsets.add(Charset(161, 'utf32', 'utf32_icelandic_ci', ''))
_charsets.add(Charset(162, 'utf32', 'utf32_latvian_ci', ''))
_charsets.add(Charset(163, 'utf32', 'utf32_romanian_ci', ''))
_charsets.add(Charset(164, 'utf32', 'utf32_slovenian_ci', ''))
_charsets.add(Charset(165, 'utf32', 'utf32_polish_ci', ''))
_charsets.add(Charset(166, 'utf32', 'utf32_estonian_ci', ''))
_charsets.add(Charset(167, 'utf32', 'utf32_spanish_ci', ''))
_charsets.add(Charset(168, 'utf32', 'utf32_swedish_ci', ''))
_charsets.add(Charset(169, 'utf32', 'utf32_turkish_ci', ''))
_charsets.add(Charset(170, 'utf32', 'utf32_czech_ci', ''))
_charsets.add(Charset(171, 'utf32', 'utf32_danish_ci', ''))
_charsets.add(Charset(172, 'utf32', 'utf32_lithuanian_ci', ''))
_charsets.add(Charset(173, 'utf32', 'utf32_slovak_ci', ''))
_charsets.add(Charset(174, 'utf32', 'utf32_spanish2_ci', ''))
_charsets.add(Charset(175, 'utf32', 'utf32_roman_ci', ''))
_charsets.add(Charset(176, 'utf32', 'utf32_persian_ci', ''))
_charsets.add(Charset(177, 'utf32', 'utf32_esperanto_ci', ''))
_charsets.add(Charset(178, 'utf32', 'utf32_hungarian_ci', ''))
_charsets.add(Charset(179, 'utf32', 'utf32_sinhala_ci', ''))
_charsets.add(Charset(192, 'utf8', 'utf8_unicode_ci', ''))
_charsets.add(Charset(193, 'utf8', 'utf8_icelandic_ci', ''))
_charsets.add(Charset(194, 'utf8', 'utf8_latvian_ci', ''))
_charsets.add(Charset(195, 'utf8', 'utf8_romanian_ci', ''))
_charsets.add(Charset(196, 'utf8', 'utf8_slovenian_ci', ''))
_charsets.add(Charset(197, 'utf8', 'utf8_polish_ci', ''))
_charsets.add(Charset(198, 'utf8', 'utf8_estonian_ci', ''))
_charsets.add(Charset(199, 'utf8', 'utf8_spanish_ci', ''))
_charsets.add(Charset(200, 'utf8', 'utf8_swedish_ci', ''))
_charsets.add(Charset(201, 'utf8', 'utf8_turkish_ci', ''))
_charsets.add(Charset(202, 'utf8', 'utf8_czech_ci', ''))
_charsets.add(Charset(203, 'utf8', 'utf8_danish_ci', ''))
_charsets.add(Charset(204, 'utf8', 'utf8_lithuanian_ci', ''))
_charsets.add(Charset(205, 'utf8', 'utf8_slovak_ci', ''))
_charsets.add(Charset(206, 'utf8', 'utf8_spanish2_ci', ''))
_charsets.add(Charset(207, 'utf8', 'utf8_roman_ci', ''))
_charsets.add(Charset(208, 'utf8', 'utf8_persian_ci', ''))
_charsets.add(Charset(209, 'utf8', 'utf8_esperanto_ci', ''))
_charsets.add(Charset(210, 'utf8', 'utf8_hungarian_ci', ''))
_charsets.add(Charset(211, 'utf8', 'utf8_sinhala_ci', ''))
_charsets.add(Charset(223, 'utf8', 'utf8_general_mysql500_ci', ''))
_charsets.add(Charset(224, 'utf8mb4', 'utf8mb4_unicode_ci', ''))
_charsets.add(Charset(225, 'utf8mb4', 'utf8mb4_icelandic_ci', ''))
_charsets.add(Charset(226, 'utf8mb4', 'utf8mb4_latvian_ci', ''))
_charsets.add(Charset(227, 'utf8mb4', 'utf8mb4_romanian_ci', ''))
_charsets.add(Charset(228, 'utf8mb4', 'utf8mb4_slovenian_ci', ''))
_charsets.add(Charset(229, 'utf8mb4', 'utf8mb4_polish_ci', ''))
_charsets.add(Charset(230, 'utf8mb4', 'utf8mb4_estonian_ci', ''))
_charsets.add(Charset(231, 'utf8mb4', 'utf8mb4_spanish_ci', ''))
_charsets.add(Charset(232, 'utf8mb4', 'utf8mb4_swedish_ci', ''))
_charsets.add(Charset(233, 'utf8mb4', 'utf8mb4_turkish_ci', ''))
_charsets.add(Charset(234, 'utf8mb4', 'utf8mb4_czech_ci', ''))
_charsets.add(Charset(235, 'utf8mb4', 'utf8mb4_danish_ci', ''))
_charsets.add(Charset(236, 'utf8mb4', 'utf8mb4_lithuanian_ci', ''))
_charsets.add(Charset(237, 'utf8mb4', 'utf8mb4_slovak_ci', ''))
_charsets.add(Charset(238, 'utf8mb4', 'utf8mb4_spanish2_ci', ''))
_charsets.add(Charset(239, 'utf8mb4', 'utf8mb4_roman_ci', ''))
_charsets.add(Charset(240, 'utf8mb4', 'utf8mb4_persian_ci', ''))
_charsets.add(Charset(241, 'utf8mb4', 'utf8mb4_esperanto_ci', ''))
_charsets.add(Charset(242, 'utf8mb4', 'utf8mb4_hungarian_ci', ''))
_charsets.add(Charset(243, 'utf8mb4', 'utf8mb4_sinhala_ci', ''))
_charsets.add(Charset(244, 'utf8mb4', 'utf8mb4_german2_ci', ''))
_charsets.add(Charset(245, 'utf8mb4', 'utf8mb4_croatian_ci', ''))
_charsets.add(Charset(246, 'utf8mb4', 'utf8mb4_unicode_520_ci', ''))
_charsets.add(Charset(247, 'utf8mb4', 'utf8mb4_vietnamese_ci', ''))
charset_by_name = _charsets.by_name
charset_by_id = _charsets.by_id
def charset_to_encoding(name):
"""Convert MySQL's charset name to Python's codec name"""
if name == 'utf8mb4':
return 'utf8'
return name | ytp1 | /ytp1-6.3.12-cp36-cp36m-win_amd64.whl/pymysql/charset.py | charset.py |
import struct
from . import ER
class MySQLError(Exception):
"""Exception related to operation with MySQL."""
class Warning(Warning, MySQLError):
"""Exception raised for important warnings like data truncations
while inserting, etc."""
class Error(MySQLError):
"""Exception that is the base class of all other error exceptions
(not Warning)."""
class InterfaceError(Error):
"""Exception raised for errors that are related to the database
interface rather than the database itself."""
class DatabaseError(Error):
"""Exception raised for errors that are related to the
database."""
class DataError(DatabaseError):
"""Exception raised for errors that are due to problems with the
processed data like division by zero, numeric value out of range,
etc."""
class OperationalError(DatabaseError):
"""Exception raised for errors that are related to the database's
operation and not necessarily under the control of the programmer,
e.g. an unexpected disconnect occurs, the data source name is not
found, a transaction could not be processed, a memory allocation
error occurred during processing, etc."""
class IntegrityError(DatabaseError):
"""Exception raised when the relational integrity of the database
is affected, e.g. a foreign key check fails, duplicate key,
etc."""
class InternalError(DatabaseError):
"""Exception raised when the database encounters an internal
error, e.g. the cursor is not valid anymore, the transaction is
out of sync, etc."""
class ProgrammingError(DatabaseError):
"""Exception raised for programming errors, e.g. table not found
or already exists, syntax error in the SQL statement, wrong number
of parameters specified, etc."""
class NotSupportedError(DatabaseError):
"""Exception raised in case a method or database API was used
which is not supported by the database, e.g. requesting a
.rollback() on a connection that does not support transaction or
has transactions turned off."""
error_map = {}
def _map_error(exc, *errors):
for error in errors:
error_map[error] = exc
_map_error(ProgrammingError, ER.DB_CREATE_EXISTS, ER.SYNTAX_ERROR,
ER.PARSE_ERROR, ER.NO_SUCH_TABLE, ER.WRONG_DB_NAME,
ER.WRONG_TABLE_NAME, ER.FIELD_SPECIFIED_TWICE,
ER.INVALID_GROUP_FUNC_USE, ER.UNSUPPORTED_EXTENSION,
ER.TABLE_MUST_HAVE_COLUMNS, ER.CANT_DO_THIS_DURING_AN_TRANSACTION,
ER.WRONG_DB_NAME, ER.WRONG_COLUMN_NAME,
)
_map_error(DataError, ER.WARN_DATA_TRUNCATED, ER.WARN_NULL_TO_NOTNULL,
ER.WARN_DATA_OUT_OF_RANGE, ER.NO_DEFAULT, ER.PRIMARY_CANT_HAVE_NULL,
ER.DATA_TOO_LONG, ER.DATETIME_FUNCTION_OVERFLOW)
_map_error(IntegrityError, ER.DUP_ENTRY, ER.NO_REFERENCED_ROW,
ER.NO_REFERENCED_ROW_2, ER.ROW_IS_REFERENCED, ER.ROW_IS_REFERENCED_2,
ER.CANNOT_ADD_FOREIGN, ER.BAD_NULL_ERROR)
_map_error(NotSupportedError, ER.WARNING_NOT_COMPLETE_ROLLBACK,
ER.NOT_SUPPORTED_YET, ER.FEATURE_DISABLED, ER.UNKNOWN_STORAGE_ENGINE)
_map_error(OperationalError, ER.DBACCESS_DENIED_ERROR, ER.ACCESS_DENIED_ERROR,
ER.CON_COUNT_ERROR, ER.TABLEACCESS_DENIED_ERROR,
ER.COLUMNACCESS_DENIED_ERROR, ER.CONSTRAINT_FAILED, ER.LOCK_DEADLOCK)
del _map_error, ER
def raise_mysql_exception(data):
errno = struct.unpack('<h', data[1:3])[0]
is_41 = data[3:4] == b"#"
if is_41:
# client protocol 4.1
errval = data[9:].decode('utf-8', 'replace')
else:
errval = data[3:].decode('utf-8', 'replace')
errorclass = error_map.get(errno, InternalError)
raise errorclass(errno, errval) | ytp1 | /ytp1-6.3.12-cp36-cp36m-win_amd64.whl/pymysql/err.py | err.py |
from ._compat import text_type, PY2
from . import CLIENT
from .err import OperationalError
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from functools import partial
import hashlib
import struct
DEBUG = False
SCRAMBLE_LENGTH = 20
sha1_new = partial(hashlib.new, 'sha1')
# mysql_native_password
# https://dev.mysql.com/doc/internals/en/secure-password-authentication.html#packet-Authentication::Native41
def scramble_native_password(password, message):
"""Scramble used for mysql_native_password"""
if not password:
return b''
stage1 = sha1_new(password).digest()
stage2 = sha1_new(stage1).digest()
s = sha1_new()
s.update(message[:SCRAMBLE_LENGTH])
s.update(stage2)
result = s.digest()
return _my_crypt(result, stage1)
def _my_crypt(message1, message2):
result = bytearray(message1)
if PY2:
message2 = bytearray(message2)
for i in range(len(result)):
result[i] ^= message2[i]
return bytes(result)
# old_passwords support ported from libmysql/password.c
# https://dev.mysql.com/doc/internals/en/old-password-authentication.html
SCRAMBLE_LENGTH_323 = 8
class RandStruct_323(object):
def __init__(self, seed1, seed2):
self.max_value = 0x3FFFFFFF
self.seed1 = seed1 % self.max_value
self.seed2 = seed2 % self.max_value
def my_rnd(self):
self.seed1 = (self.seed1 * 3 + self.seed2) % self.max_value
self.seed2 = (self.seed1 + self.seed2 + 33) % self.max_value
return float(self.seed1) / float(self.max_value)
def scramble_old_password(password, message):
"""Scramble for old_password"""
hash_pass = _hash_password_323(password)
hash_message = _hash_password_323(message[:SCRAMBLE_LENGTH_323])
hash_pass_n = struct.unpack(">LL", hash_pass)
hash_message_n = struct.unpack(">LL", hash_message)
rand_st = RandStruct_323(
hash_pass_n[0] ^ hash_message_n[0], hash_pass_n[1] ^ hash_message_n[1]
)
outbuf = io.BytesIO()
for _ in range(min(SCRAMBLE_LENGTH_323, len(message))):
outbuf.write(int2byte(int(rand_st.my_rnd() * 31) + 64))
extra = int2byte(int(rand_st.my_rnd() * 31))
out = outbuf.getvalue()
outbuf = io.BytesIO()
for c in out:
outbuf.write(int2byte(byte2int(c) ^ byte2int(extra)))
return outbuf.getvalue()
def _hash_password_323(password):
nr = 1345345333
add = 7
nr2 = 0x12345671
# x in py3 is numbers, p27 is chars
for c in [byte2int(x) for x in password if x not in (' ', '\t', 32, 9)]:
nr ^= (((nr & 63) + add) * c) + (nr << 8) & 0xFFFFFFFF
nr2 = (nr2 + ((nr2 << 8) ^ nr)) & 0xFFFFFFFF
add = (add + c) & 0xFFFFFFFF
r1 = nr & ((1 << 31) - 1) # kill sign bits
r2 = nr2 & ((1 << 31) - 1)
return struct.pack(">LL", r1, r2)
# sha256_password
def _roundtrip(conn, send_data):
conn.write_packet(send_data)
pkt = conn._read_packet()
pkt.check_error()
return pkt
def _xor_password(password, salt):
password_bytes = bytearray(password)
salt = bytearray(salt) # for PY2 compat.
salt_len = len(salt)
for i in range(len(password_bytes)):
password_bytes[i] ^= salt[i % salt_len]
return bytes(password_bytes)
def sha2_rsa_encrypt(password, salt, public_key):
"""Encrypt password with salt and public_key.
Used for sha256_password and caching_sha2_password.
"""
message = _xor_password(password + b'\0', salt)
rsa_key = serialization.load_pem_public_key(public_key, default_backend())
return rsa_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None,
),
)
def sha256_password_auth(conn, pkt):
if conn._secure:
if DEBUG:
print("sha256: Sending plain password")
data = conn.password + b'\0'
return _roundtrip(conn, data)
if pkt.is_auth_switch_request():
conn.salt = pkt.read_all()
if not conn.server_public_key and conn.password:
# Request server public key
if DEBUG:
print("sha256: Requesting server public key")
pkt = _roundtrip(conn, b'\1')
if pkt.is_extra_auth_data():
conn.server_public_key = pkt._data[1:]
if DEBUG:
print("Received public key:\n", conn.server_public_key.decode('ascii'))
if conn.password:
if not conn.server_public_key:
raise OperationalError("Couldn't receive server's public key")
data = sha2_rsa_encrypt(conn.password, conn.salt, conn.server_public_key)
else:
data = b''
return _roundtrip(conn, data)
def scramble_caching_sha2(password, nonce):
# (bytes, bytes) -> bytes
"""Scramble algorithm used in cached_sha2_password fast path.
XOR(SHA256(password), SHA256(SHA256(SHA256(password)), nonce))
"""
if not password:
return b''
p1 = hashlib.sha256(password).digest()
p2 = hashlib.sha256(p1).digest()
p3 = hashlib.sha256(p2 + nonce).digest()
res = bytearray(p1)
if PY2:
p3 = bytearray(p3)
for i in range(len(p3)):
res[i] ^= p3[i]
return bytes(res)
def caching_sha2_password_auth(conn, pkt):
# No password fast path
if not conn.password:
return _roundtrip(conn, b'')
if pkt.is_auth_switch_request():
# Try from fast auth
if DEBUG:
print("caching sha2: Trying fast path")
conn.salt = pkt.read_all()
scrambled = scramble_caching_sha2(conn.password, conn.salt)
pkt = _roundtrip(conn, scrambled)
# else: fast auth is tried in initial handshake
if not pkt.is_extra_auth_data():
raise OperationalError(
"caching sha2: Unknown packet for fast auth: %s" % pkt._data[:1]
)
# magic numbers:
# 2 - request public key
# 3 - fast auth succeeded
# 4 - need full auth
pkt.advance(1)
n = pkt.read_uint8()
if n == 3:
if DEBUG:
print("caching sha2: succeeded by fast path.")
pkt = conn._read_packet()
pkt.check_error() # pkt must be OK packet
return pkt
if n != 4:
raise OperationalError("caching sha2: Unknwon result for fast auth: %s" % n)
if DEBUG:
print("caching sha2: Trying full auth...")
if conn._secure:
if DEBUG:
print("caching sha2: Sending plain password via secure connection")
return _roundtrip(conn, conn.password + b'\0')
if not conn.server_public_key:
pkt = _roundtrip(conn, b'\x02') # Request public key
if not pkt.is_extra_auth_data():
raise OperationalError(
"caching sha2: Unknown packet for public key: %s" % pkt._data[:1]
)
conn.server_public_key = pkt._data[1:]
if DEBUG:
print(conn.server_public_key.decode('ascii'))
data = sha2_rsa_encrypt(conn.password, conn.salt, conn.server_public_key)
pkt = _roundtrip(conn, data) | ytp1 | /ytp1-6.3.12-cp36-cp36m-win_amd64.whl/pymysql/_auth.py | _auth.py |
ERROR_FIRST = 1000
HASHCHK = 1000
NISAMCHK = 1001
NO = 1002
YES = 1003
CANT_CREATE_FILE = 1004
CANT_CREATE_TABLE = 1005
CANT_CREATE_DB = 1006
DB_CREATE_EXISTS = 1007
DB_DROP_EXISTS = 1008
DB_DROP_DELETE = 1009
DB_DROP_RMDIR = 1010
CANT_DELETE_FILE = 1011
CANT_FIND_SYSTEM_REC = 1012
CANT_GET_STAT = 1013
CANT_GET_WD = 1014
CANT_LOCK = 1015
CANT_OPEN_FILE = 1016
FILE_NOT_FOUND = 1017
CANT_READ_DIR = 1018
CANT_SET_WD = 1019
CHECKREAD = 1020
DISK_FULL = 1021
DUP_KEY = 1022
ERROR_ON_CLOSE = 1023
ERROR_ON_READ = 1024
ERROR_ON_RENAME = 1025
ERROR_ON_WRITE = 1026
FILE_USED = 1027
FILSORT_ABORT = 1028
FORM_NOT_FOUND = 1029
GET_ERRNO = 1030
ILLEGAL_HA = 1031
KEY_NOT_FOUND = 1032
NOT_FORM_FILE = 1033
NOT_KEYFILE = 1034
OLD_KEYFILE = 1035
OPEN_AS_READONLY = 1036
OUTOFMEMORY = 1037
OUT_OF_SORTMEMORY = 1038
UNEXPECTED_EOF = 1039
CON_COUNT_ERROR = 1040
OUT_OF_RESOURCES = 1041
BAD_HOST_ERROR = 1042
HANDSHAKE_ERROR = 1043
DBACCESS_DENIED_ERROR = 1044
ACCESS_DENIED_ERROR = 1045
NO_DB_ERROR = 1046
UNKNOWN_COM_ERROR = 1047
BAD_NULL_ERROR = 1048
BAD_DB_ERROR = 1049
TABLE_EXISTS_ERROR = 1050
BAD_TABLE_ERROR = 1051
NON_UNIQ_ERROR = 1052
SERVER_SHUTDOWN = 1053
BAD_FIELD_ERROR = 1054
WRONG_FIELD_WITH_GROUP = 1055
WRONG_GROUP_FIELD = 1056
WRONG_SUM_SELECT = 1057
WRONG_VALUE_COUNT = 1058
TOO_LONG_IDENT = 1059
DUP_FIELDNAME = 1060
DUP_KEYNAME = 1061
DUP_ENTRY = 1062
WRONG_FIELD_SPEC = 1063
PARSE_ERROR = 1064
EMPTY_QUERY = 1065
NONUNIQ_TABLE = 1066
INVALID_DEFAULT = 1067
MULTIPLE_PRI_KEY = 1068
TOO_MANY_KEYS = 1069
TOO_MANY_KEY_PARTS = 1070
TOO_LONG_KEY = 1071
KEY_COLUMN_DOES_NOT_EXITS = 1072
BLOB_USED_AS_KEY = 1073
TOO_BIG_FIELDLENGTH = 1074
WRONG_AUTO_KEY = 1075
READY = 1076
NORMAL_SHUTDOWN = 1077
GOT_SIGNAL = 1078
SHUTDOWN_COMPLETE = 1079
FORCING_CLOSE = 1080
IPSOCK_ERROR = 1081
NO_SUCH_INDEX = 1082
WRONG_FIELD_TERMINATORS = 1083
BLOBS_AND_NO_TERMINATED = 1084
TEXTFILE_NOT_READABLE = 1085
FILE_EXISTS_ERROR = 1086
LOAD_INFO = 1087
ALTER_INFO = 1088
WRONG_SUB_KEY = 1089
CANT_REMOVE_ALL_FIELDS = 1090
CANT_DROP_FIELD_OR_KEY = 1091
INSERT_INFO = 1092
UPDATE_TABLE_USED = 1093
NO_SUCH_THREAD = 1094
KILL_DENIED_ERROR = 1095
NO_TABLES_USED = 1096
TOO_BIG_SET = 1097
NO_UNIQUE_LOGFILE = 1098
TABLE_NOT_LOCKED_FOR_WRITE = 1099
TABLE_NOT_LOCKED = 1100
BLOB_CANT_HAVE_DEFAULT = 1101
WRONG_DB_NAME = 1102
WRONG_TABLE_NAME = 1103
TOO_BIG_SELECT = 1104
UNKNOWN_ERROR = 1105
UNKNOWN_PROCEDURE = 1106
WRONG_PARAMCOUNT_TO_PROCEDURE = 1107
WRONG_PARAMETERS_TO_PROCEDURE = 1108
UNKNOWN_TABLE = 1109
FIELD_SPECIFIED_TWICE = 1110
INVALID_GROUP_FUNC_USE = 1111
UNSUPPORTED_EXTENSION = 1112
TABLE_MUST_HAVE_COLUMNS = 1113
RECORD_FILE_FULL = 1114
UNKNOWN_CHARACTER_SET = 1115
TOO_MANY_TABLES = 1116
TOO_MANY_FIELDS = 1117
TOO_BIG_ROWSIZE = 1118
STACK_OVERRUN = 1119
WRONG_OUTER_JOIN = 1120
NULL_COLUMN_IN_INDEX = 1121
CANT_FIND_UDF = 1122
CANT_INITIALIZE_UDF = 1123
UDF_NO_PATHS = 1124
UDF_EXISTS = 1125
CANT_OPEN_LIBRARY = 1126
CANT_FIND_DL_ENTRY = 1127
FUNCTION_NOT_DEFINED = 1128
HOST_IS_BLOCKED = 1129
HOST_NOT_PRIVILEGED = 1130
PASSWORD_ANONYMOUS_USER = 1131
PASSWORD_NOT_ALLOWED = 1132
PASSWORD_NO_MATCH = 1133
UPDATE_INFO = 1134
CANT_CREATE_THREAD = 1135
WRONG_VALUE_COUNT_ON_ROW = 1136
CANT_REOPEN_TABLE = 1137
INVALID_USE_OF_NULL = 1138
REGEXP_ERROR = 1139
MIX_OF_GROUP_FUNC_AND_FIELDS = 1140
NONEXISTING_GRANT = 1141
TABLEACCESS_DENIED_ERROR = 1142
COLUMNACCESS_DENIED_ERROR = 1143
ILLEGAL_GRANT_FOR_TABLE = 1144
GRANT_WRONG_HOST_OR_USER = 1145
NO_SUCH_TABLE = 1146
NONEXISTING_TABLE_GRANT = 1147
NOT_ALLOWED_COMMAND = 1148
SYNTAX_ERROR = 1149
DELAYED_CANT_CHANGE_LOCK = 1150
TOO_MANY_DELAYED_THREADS = 1151
ABORTING_CONNECTION = 1152
NET_PACKET_TOO_LARGE = 1153
NET_READ_ERROR_FROM_PIPE = 1154
NET_FCNTL_ERROR = 1155
NET_PACKETS_OUT_OF_ORDER = 1156
NET_UNCOMPRESS_ERROR = 1157
NET_READ_ERROR = 1158
NET_READ_INTERRUPTED = 1159
NET_ERROR_ON_WRITE = 1160
NET_WRITE_INTERRUPTED = 1161
TOO_LONG_STRING = 1162
TABLE_CANT_HANDLE_BLOB = 1163
TABLE_CANT_HANDLE_AUTO_INCREMENT = 1164
DELAYED_INSERT_TABLE_LOCKED = 1165
WRONG_COLUMN_NAME = 1166
WRONG_KEY_COLUMN = 1167
WRONG_MRG_TABLE = 1168
DUP_UNIQUE = 1169
BLOB_KEY_WITHOUT_LENGTH = 1170
PRIMARY_CANT_HAVE_NULL = 1171
TOO_MANY_ROWS = 1172
REQUIRES_PRIMARY_KEY = 1173
NO_RAID_COMPILED = 1174
UPDATE_WITHOUT_KEY_IN_SAFE_MODE = 1175
KEY_DOES_NOT_EXITS = 1176
CHECK_NO_SUCH_TABLE = 1177
CHECK_NOT_IMPLEMENTED = 1178
CANT_DO_THIS_DURING_AN_TRANSACTION = 1179
ERROR_DURING_COMMIT = 1180
ERROR_DURING_ROLLBACK = 1181
ERROR_DURING_FLUSH_LOGS = 1182
ERROR_DURING_CHECKPOINT = 1183
NEW_ABORTING_CONNECTION = 1184
DUMP_NOT_IMPLEMENTED = 1185
FLUSH_MASTER_BINLOG_CLOSED = 1186
INDEX_REBUILD = 1187
MASTER = 1188
MASTER_NET_READ = 1189
MASTER_NET_WRITE = 1190
FT_MATCHING_KEY_NOT_FOUND = 1191
LOCK_OR_ACTIVE_TRANSACTION = 1192
UNKNOWN_SYSTEM_VARIABLE = 1193
CRASHED_ON_USAGE = 1194
CRASHED_ON_REPAIR = 1195
WARNING_NOT_COMPLETE_ROLLBACK = 1196
TRANS_CACHE_FULL = 1197
SLAVE_MUST_STOP = 1198
SLAVE_NOT_RUNNING = 1199
BAD_SLAVE = 1200
MASTER_INFO = 1201
SLAVE_THREAD = 1202
TOO_MANY_USER_CONNECTIONS = 1203
SET_CONSTANTS_ONLY = 1204
LOCK_WAIT_TIMEOUT = 1205
LOCK_TABLE_FULL = 1206
READ_ONLY_TRANSACTION = 1207
DROP_DB_WITH_READ_LOCK = 1208
CREATE_DB_WITH_READ_LOCK = 1209
WRONG_ARGUMENTS = 1210
NO_PERMISSION_TO_CREATE_USER = 1211
UNION_TABLES_IN_DIFFERENT_DIR = 1212
LOCK_DEADLOCK = 1213
TABLE_CANT_HANDLE_FT = 1214
CANNOT_ADD_FOREIGN = 1215
NO_REFERENCED_ROW = 1216
ROW_IS_REFERENCED = 1217
CONNECT_TO_MASTER = 1218
QUERY_ON_MASTER = 1219
ERROR_WHEN_EXECUTING_COMMAND = 1220
WRONG_USAGE = 1221
WRONG_NUMBER_OF_COLUMNS_IN_SELECT = 1222
CANT_UPDATE_WITH_READLOCK = 1223
MIXING_NOT_ALLOWED = 1224
DUP_ARGUMENT = 1225
USER_LIMIT_REACHED = 1226
SPECIFIC_ACCESS_DENIED_ERROR = 1227
LOCAL_VARIABLE = 1228
GLOBAL_VARIABLE = 1229
NO_DEFAULT = 1230
WRONG_VALUE_FOR_VAR = 1231
WRONG_TYPE_FOR_VAR = 1232
VAR_CANT_BE_READ = 1233
CANT_USE_OPTION_HERE = 1234
NOT_SUPPORTED_YET = 1235
MASTER_FATAL_ERROR_READING_BINLOG = 1236
SLAVE_IGNORED_TABLE = 1237
INCORRECT_GLOBAL_LOCAL_VAR = 1238
WRONG_FK_DEF = 1239
KEY_REF_DO_NOT_MATCH_TABLE_REF = 1240
OPERAND_COLUMNS = 1241
SUBQUERY_NO_1_ROW = 1242
UNKNOWN_STMT_HANDLER = 1243
CORRUPT_HELP_DB = 1244
CYCLIC_REFERENCE = 1245
AUTO_CONVERT = 1246
ILLEGAL_REFERENCE = 1247
DERIVED_MUST_HAVE_ALIAS = 1248
SELECT_REDUCED = 1249
TABLENAME_NOT_ALLOWED_HERE = 1250
NOT_SUPPORTED_AUTH_MODE = 1251
SPATIAL_CANT_HAVE_NULL = 1252
COLLATION_CHARSET_MISMATCH = 1253
SLAVE_WAS_RUNNING = 1254
SLAVE_WAS_NOT_RUNNING = 1255
TOO_BIG_FOR_UNCOMPRESS = 1256
ZLIB_Z_MEM_ERROR = 1257
ZLIB_Z_BUF_ERROR = 1258
ZLIB_Z_DATA_ERROR = 1259
CUT_VALUE_GROUP_CONCAT = 1260
WARN_TOO_FEW_RECORDS = 1261
WARN_TOO_MANY_RECORDS = 1262
WARN_NULL_TO_NOTNULL = 1263
WARN_DATA_OUT_OF_RANGE = 1264
WARN_DATA_TRUNCATED = 1265
WARN_USING_OTHER_HANDLER = 1266
CANT_AGGREGATE_2COLLATIONS = 1267
DROP_USER = 1268
REVOKE_GRANTS = 1269
CANT_AGGREGATE_3COLLATIONS = 1270
CANT_AGGREGATE_NCOLLATIONS = 1271
VARIABLE_IS_NOT_STRUCT = 1272
UNKNOWN_COLLATION = 1273
SLAVE_IGNORED_SSL_PARAMS = 1274
SERVER_IS_IN_SECURE_AUTH_MODE = 1275
WARN_FIELD_RESOLVED = 1276
BAD_SLAVE_UNTIL_COND = 1277
MISSING_SKIP_SLAVE = 1278
UNTIL_COND_IGNORED = 1279
WRONG_NAME_FOR_INDEX = 1280
WRONG_NAME_FOR_CATALOG = 1281
WARN_QC_RESIZE = 1282
BAD_FT_COLUMN = 1283
UNKNOWN_KEY_CACHE = 1284
WARN_HOSTNAME_WONT_WORK = 1285
UNKNOWN_STORAGE_ENGINE = 1286
WARN_DEPRECATED_SYNTAX = 1287
NON_UPDATABLE_TABLE = 1288
FEATURE_DISABLED = 1289
OPTION_PREVENTS_STATEMENT = 1290
DUPLICATED_VALUE_IN_TYPE = 1291
TRUNCATED_WRONG_VALUE = 1292
TOO_MUCH_AUTO_TIMESTAMP_COLS = 1293
INVALID_ON_UPDATE = 1294
UNSUPPORTED_PS = 1295
GET_ERRMSG = 1296
GET_TEMPORARY_ERRMSG = 1297
UNKNOWN_TIME_ZONE = 1298
WARN_INVALID_TIMESTAMP = 1299
INVALID_CHARACTER_STRING = 1300
WARN_ALLOWED_PACKET_OVERFLOWED = 1301
CONFLICTING_DECLARATIONS = 1302
SP_NO_RECURSIVE_CREATE = 1303
SP_ALREADY_EXISTS = 1304
SP_DOES_NOT_EXIST = 1305
SP_DROP_FAILED = 1306
SP_STORE_FAILED = 1307
SP_LILABEL_MISMATCH = 1308
SP_LABEL_REDEFINE = 1309
SP_LABEL_MISMATCH = 1310
SP_UNINIT_VAR = 1311
SP_BADSELECT = 1312
SP_BADRETURN = 1313
SP_BADSTATEMENT = 1314
UPDATE_LOG_DEPRECATED_IGNORED = 1315
UPDATE_LOG_DEPRECATED_TRANSLATED = 1316
QUERY_INTERRUPTED = 1317
SP_WRONG_NO_OF_ARGS = 1318
SP_COND_MISMATCH = 1319
SP_NORETURN = 1320
SP_NORETURNEND = 1321
SP_BAD_CURSOR_QUERY = 1322
SP_BAD_CURSOR_SELECT = 1323
SP_CURSOR_MISMATCH = 1324
SP_CURSOR_ALREADY_OPEN = 1325
SP_CURSOR_NOT_OPEN = 1326
SP_UNDECLARED_VAR = 1327
SP_WRONG_NO_OF_FETCH_ARGS = 1328
SP_FETCH_NO_DATA = 1329
SP_DUP_PARAM = 1330
SP_DUP_VAR = 1331
SP_DUP_COND = 1332
SP_DUP_CURS = 1333
SP_CANT_ALTER = 1334
SP_SUBSELECT_NYI = 1335
STMT_NOT_ALLOWED_IN_SF_OR_TRG = 1336
SP_VARCOND_AFTER_CURSHNDLR = 1337
SP_CURSOR_AFTER_HANDLER = 1338
SP_CASE_NOT_FOUND = 1339
FPARSER_TOO_BIG_FILE = 1340
FPARSER_BAD_HEADER = 1341
FPARSER_EOF_IN_COMMENT = 1342
FPARSER_ERROR_IN_PARAMETER = 1343
FPARSER_EOF_IN_UNKNOWN_PARAMETER = 1344
VIEW_NO_EXPLAIN = 1345
FRM_UNKNOWN_TYPE = 1346
WRONG_OBJECT = 1347
NONUPDATEABLE_COLUMN = 1348
VIEW_SELECT_DERIVED = 1349
VIEW_SELECT_CLAUSE = 1350
VIEW_SELECT_VARIABLE = 1351
VIEW_SELECT_TMPTABLE = 1352
VIEW_WRONG_LIST = 1353
WARN_VIEW_MERGE = 1354
WARN_VIEW_WITHOUT_KEY = 1355
VIEW_INVALID = 1356
SP_NO_DROP_SP = 1357
SP_GOTO_IN_HNDLR = 1358
TRG_ALREADY_EXISTS = 1359
TRG_DOES_NOT_EXIST = 1360
TRG_ON_VIEW_OR_TEMP_TABLE = 1361
TRG_CANT_CHANGE_ROW = 1362
TRG_NO_SUCH_ROW_IN_TRG = 1363
NO_DEFAULT_FOR_FIELD = 1364
DIVISION_BY_ZERO = 1365
TRUNCATED_WRONG_VALUE_FOR_FIELD = 1366
ILLEGAL_VALUE_FOR_TYPE = 1367
VIEW_NONUPD_CHECK = 1368
VIEW_CHECK_FAILED = 1369
PROCACCESS_DENIED_ERROR = 1370
RELAY_LOG_FAIL = 1371
PASSWD_LENGTH = 1372
UNKNOWN_TARGET_BINLOG = 1373
IO_ERR_LOG_INDEX_READ = 1374
BINLOG_PURGE_PROHIBITED = 1375
FSEEK_FAIL = 1376
BINLOG_PURGE_FATAL_ERR = 1377
LOG_IN_USE = 1378
LOG_PURGE_UNKNOWN_ERR = 1379
RELAY_LOG_INIT = 1380
NO_BINARY_LOGGING = 1381
RESERVED_SYNTAX = 1382
WSAS_FAILED = 1383
DIFF_GROUPS_PROC = 1384
NO_GROUP_FOR_PROC = 1385
ORDER_WITH_PROC = 1386
LOGGING_PROHIBIT_CHANGING_OF = 1387
NO_FILE_MAPPING = 1388
WRONG_MAGIC = 1389
PS_MANY_PARAM = 1390
KEY_PART_0 = 1391
VIEW_CHECKSUM = 1392
VIEW_MULTIUPDATE = 1393
VIEW_NO_INSERT_FIELD_LIST = 1394
VIEW_DELETE_MERGE_VIEW = 1395
CANNOT_USER = 1396
XAER_NOTA = 1397
XAER_INVAL = 1398
XAER_RMFAIL = 1399
XAER_OUTSIDE = 1400
XAER_RMERR = 1401
XA_RBROLLBACK = 1402
NONEXISTING_PROC_GRANT = 1403
PROC_AUTO_GRANT_FAIL = 1404
PROC_AUTO_REVOKE_FAIL = 1405
DATA_TOO_LONG = 1406
SP_BAD_SQLSTATE = 1407
STARTUP = 1408
LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR = 1409
CANT_CREATE_USER_WITH_GRANT = 1410
WRONG_VALUE_FOR_TYPE = 1411
TABLE_DEF_CHANGED = 1412
SP_DUP_HANDLER = 1413
SP_NOT_VAR_ARG = 1414
SP_NO_RETSET = 1415
CANT_CREATE_GEOMETRY_OBJECT = 1416
FAILED_ROUTINE_BREAK_BINLOG = 1417
BINLOG_UNSAFE_ROUTINE = 1418
BINLOG_CREATE_ROUTINE_NEED_SUPER = 1419
EXEC_STMT_WITH_OPEN_CURSOR = 1420
STMT_HAS_NO_OPEN_CURSOR = 1421
COMMIT_NOT_ALLOWED_IN_SF_OR_TRG = 1422
NO_DEFAULT_FOR_VIEW_FIELD = 1423
SP_NO_RECURSION = 1424
TOO_BIG_SCALE = 1425
TOO_BIG_PRECISION = 1426
M_BIGGER_THAN_D = 1427
WRONG_LOCK_OF_SYSTEM_TABLE = 1428
CONNECT_TO_FOREIGN_DATA_SOURCE = 1429
QUERY_ON_FOREIGN_DATA_SOURCE = 1430
FOREIGN_DATA_SOURCE_DOESNT_EXIST = 1431
FOREIGN_DATA_STRING_INVALID_CANT_CREATE = 1432
FOREIGN_DATA_STRING_INVALID = 1433
CANT_CREATE_FEDERATED_TABLE = 1434
TRG_IN_WRONG_SCHEMA = 1435
STACK_OVERRUN_NEED_MORE = 1436
TOO_LONG_BODY = 1437
WARN_CANT_DROP_DEFAULT_KEYCACHE = 1438
TOO_BIG_DISPLAYWIDTH = 1439
XAER_DUPID = 1440
DATETIME_FUNCTION_OVERFLOW = 1441
CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG = 1442
VIEW_PREVENT_UPDATE = 1443
PS_NO_RECURSION = 1444
SP_CANT_SET_AUTOCOMMIT = 1445
MALFORMED_DEFINER = 1446
VIEW_FRM_NO_USER = 1447
VIEW_OTHER_USER = 1448
NO_SUCH_USER = 1449
FORBID_SCHEMA_CHANGE = 1450
ROW_IS_REFERENCED_2 = 1451
NO_REFERENCED_ROW_2 = 1452
SP_BAD_VAR_SHADOW = 1453
TRG_NO_DEFINER = 1454
OLD_FILE_FORMAT = 1455
SP_RECURSION_LIMIT = 1456
SP_PROC_TABLE_CORRUPT = 1457
SP_WRONG_NAME = 1458
TABLE_NEEDS_UPGRADE = 1459
SP_NO_AGGREGATE = 1460
MAX_PREPARED_STMT_COUNT_REACHED = 1461
VIEW_RECURSIVE = 1462
NON_GROUPING_FIELD_USED = 1463
TABLE_CANT_HANDLE_SPKEYS = 1464
NO_TRIGGERS_ON_SYSTEM_SCHEMA = 1465
USERNAME = 1466
HOSTNAME = 1467
WRONG_STRING_LENGTH = 1468
ERROR_LAST = 1468
# https://github.com/PyMySQL/PyMySQL/issues/607
CONSTRAINT_FAILED = 4025 | ytp1 | /ytp1-6.3.12-cp36-cp36m-win_amd64.whl/pymysql/ER.py | ER.py |
CR_ERROR_FIRST = 2000
CR_UNKNOWN_ERROR = 2000
CR_SOCKET_CREATE_ERROR = 2001
CR_CONNECTION_ERROR = 2002
CR_CONN_HOST_ERROR = 2003
CR_IPSOCK_ERROR = 2004
CR_UNKNOWN_HOST = 2005
CR_SERVER_GONE_ERROR = 2006
CR_VERSION_ERROR = 2007
CR_OUT_OF_MEMORY = 2008
CR_WRONG_HOST_INFO = 2009
CR_LOCALHOST_CONNECTION = 2010
CR_TCP_CONNECTION = 2011
CR_SERVER_HANDSHAKE_ERR = 2012
CR_SERVER_LOST = 2013
CR_COMMANDS_OUT_OF_SYNC = 2014
CR_NAMEDPIPE_CONNECTION = 2015
CR_NAMEDPIPEWAIT_ERROR = 2016
CR_NAMEDPIPEOPEN_ERROR = 2017
CR_NAMEDPIPESETSTATE_ERROR = 2018
CR_CANT_READ_CHARSET = 2019
CR_NET_PACKET_TOO_LARGE = 2020
CR_EMBEDDED_CONNECTION = 2021
CR_PROBE_SLAVE_STATUS = 2022
CR_PROBE_SLAVE_HOSTS = 2023
CR_PROBE_SLAVE_CONNECT = 2024
CR_PROBE_MASTER_CONNECT = 2025
CR_SSL_CONNECTION_ERROR = 2026
CR_MALFORMED_PACKET = 2027
CR_WRONG_LICENSE = 2028
CR_NULL_POINTER = 2029
CR_NO_PREPARE_STMT = 2030
CR_PARAMS_NOT_BOUND = 2031
CR_DATA_TRUNCATED = 2032
CR_NO_PARAMETERS_EXISTS = 2033
CR_INVALID_PARAMETER_NO = 2034
CR_INVALID_BUFFER_USE = 2035
CR_UNSUPPORTED_PARAM_TYPE = 2036
CR_SHARED_MEMORY_CONNECTION = 2037
CR_SHARED_MEMORY_CONNECT_REQUEST_ERROR = 2038
CR_SHARED_MEMORY_CONNECT_ANSWER_ERROR = 2039
CR_SHARED_MEMORY_CONNECT_FILE_MAP_ERROR = 2040
CR_SHARED_MEMORY_CONNECT_MAP_ERROR = 2041
CR_SHARED_MEMORY_FILE_MAP_ERROR = 2042
CR_SHARED_MEMORY_MAP_ERROR = 2043
CR_SHARED_MEMORY_EVENT_ERROR = 2044
CR_SHARED_MEMORY_CONNECT_ABANDONED_ERROR = 2045
CR_SHARED_MEMORY_CONNECT_SET_ERROR = 2046
CR_CONN_UNKNOW_PROTOCOL = 2047
CR_INVALID_CONN_HANDLE = 2048
CR_SECURE_AUTH = 2049
CR_FETCH_CANCELED = 2050
CR_NO_DATA = 2051
CR_NO_STMT_METADATA = 2052
CR_NO_RESULT_SET = 2053
CR_NOT_IMPLEMENTED = 2054
CR_SERVER_LOST_EXTENDED = 2055
CR_STMT_CLOSED = 2056
CR_NEW_STMT_METADATA = 2057
CR_ALREADY_CONNECTED = 2058
CR_AUTH_PLUGIN_CANNOT_LOAD = 2059
CR_DUPLICATE_CONNECTION_ATTR = 2060
CR_AUTH_PLUGIN_ERR = 2061
CR_ERROR_LAST = 2061 | ytp1 | /ytp1-6.3.12-cp36-cp36m-win_amd64.whl/pymysql/CR.py | CR.py |
from __future__ import print_function
from ._compat import PY2, range_type, text_type, str_type, JYTHON, IRONPYTHON
import errno
import io
import os
import socket
import struct
import sys
import traceback
import warnings
from . import _auth
from .charset import charset_by_name, charset_by_id
from . import CLIENT, COMMAND, CR, FIELD_TYPE, SERVER_STATUS
from . import converters
from .cursors import Cursor
from .optionfile import Parser
from .protocol import (
dump_packet, MysqlPacket, FieldDescriptorPacket, OKPacketWrapper,
EOFPacketWrapper, LoadLocalPacketWrapper
)
from .util import byte2int, int2byte
from . import err, VERSION_STRING
try:
import ssl
SSL_ENABLED = True
except ImportError:
ssl = None
SSL_ENABLED = False
try:
import getpass
DEFAULT_USER = getpass.getuser()
del getpass
except (ImportError, KeyError):
# KeyError occurs when there's no entry in OS database for a current user.
DEFAULT_USER = None
DEBUG = False
_py_version = sys.version_info[:2]
if PY2:
pass
elif _py_version < (3, 6):
# See http://bugs.python.org/issue24870
_surrogateescape_table = [chr(i) if i < 0x80 else chr(i + 0xdc00) for i in range(256)]
def _fast_surrogateescape(s):
return s.decode('latin1').translate(_surrogateescape_table)
else:
def _fast_surrogateescape(s):
return s.decode('ascii', 'surrogateescape')
# socket.makefile() in Python 2 is not usable because very inefficient and
# bad behavior about timeout.
# XXX: ._socketio doesn't work under IronPython.
if PY2 and not IRONPYTHON:
# read method of file-like returned by sock.makefile() is very slow.
# So we copy io-based one from Python 3.
from ._socketio import SocketIO
def _makefile(sock, mode):
return io.BufferedReader(SocketIO(sock, mode))
else:
# socket.makefile in Python 3 is nice.
def _makefile(sock, mode):
return sock.makefile(mode)
TEXT_TYPES = {
FIELD_TYPE.BIT,
FIELD_TYPE.BLOB,
FIELD_TYPE.LONG_BLOB,
FIELD_TYPE.MEDIUM_BLOB,
FIELD_TYPE.STRING,
FIELD_TYPE.TINY_BLOB,
FIELD_TYPE.VAR_STRING,
FIELD_TYPE.VARCHAR,
FIELD_TYPE.GEOMETRY,
}
DEFAULT_CHARSET = 'utf8mb4' # TODO: change to utf8mb4
MAX_PACKET_LEN = 2**24-1
def pack_int24(n):
return struct.pack('<I', n)[:3]
# https://dev.mysql.com/doc/internals/en/integer.html#packet-Protocol::LengthEncodedInteger
def lenenc_int(i):
if (i < 0):
raise ValueError("Encoding %d is less than 0 - no representation in LengthEncodedInteger" % i)
elif (i < 0xfb):
return int2byte(i)
elif (i < (1 << 16)):
return b'\xfc' + struct.pack('<H', i)
elif (i < (1 << 24)):
return b'\xfd' + struct.pack('<I', i)[:3]
elif (i < (1 << 64)):
return b'\xfe' + struct.pack('<Q', i)
else:
raise ValueError("Encoding %x is larger than %x - no representation in LengthEncodedInteger" % (i, (1 << 64)))
class Connection(object):
"""
Representation of a socket with a mysql server.
The proper way to get an instance of this class is to call
connect().
Establish a connection to the MySQL database. Accepts several
arguments:
:param host: Host where the database server is located
:param user: Username to log in as
:param password: Password to use.
:param database: Database to use, None to not use a particular one.
:param port: MySQL port to use, default is usually OK. (default: 3306)
:param bind_address: When the client has multiple network interfaces, specify
the interface from which to connect to the host. Argument can be
a hostname or an IP address.
:param unix_socket: Optionally, you can use a unix socket rather than TCP/IP.
:param read_timeout: The timeout for reading from the connection in seconds (default: None - no timeout)
:param write_timeout: The timeout for writing to the connection in seconds (default: None - no timeout)
:param charset: Charset you want to use.
:param sql_mode: Default SQL_MODE to use.
:param read_default_file:
Specifies my.cnf file to read these parameters from under the [client] section.
:param conv:
Conversion dictionary to use instead of the default one.
This is used to provide custom marshalling and unmarshaling of types.
See converters.
:param use_unicode:
Whether or not to default to unicode strings.
This option defaults to true for Py3k.
:param client_flag: Custom flags to send to MySQL. Find potential values in constants.CLIENT.
:param cursorclass: Custom cursor class to use.
:param init_command: Initial SQL statement to run when connection is established.
:param connect_timeout: Timeout before throwing an exception when connecting.
(default: 10, min: 1, max: 31536000)
:param ssl:
A dict of arguments similar to mysql_ssl_set()'s parameters.
For now the capath and cipher arguments are not supported.
:param read_default_group: Group to read from in the configuration file.
:param compress: Not supported
:param named_pipe: Not supported
:param autocommit: Autocommit mode. None means use server default. (default: False)
:param local_infile: Boolean to enable the use of LOAD DATA LOCAL command. (default: False)
:param max_allowed_packet: Max size of packet sent to server in bytes. (default: 16MB)
Only used to limit size of "LOAD LOCAL INFILE" data packet smaller than default (16KB).
:param defer_connect: Don't explicitly connect on contruction - wait for connect call.
(default: False)
:param auth_plugin_map: A dict of plugin names to a class that processes that plugin.
The class will take the Connection object as the argument to the constructor.
The class needs an authenticate method taking an authentication packet as
an argument. For the dialog plugin, a prompt(echo, prompt) method can be used
(if no authenticate method) for returning a string from the user. (experimental)
:param server_public_key: SHA256 authenticaiton plugin public key value. (default: None)
:param db: Alias for database. (for compatibility to MySQLdb)
:param passwd: Alias for password. (for compatibility to MySQLdb)
:param binary_prefix: Add _binary prefix on bytes and bytearray. (default: False)
See `Connection <https://www.python.org/dev/peps/pep-0249/#connection-objects>`_ in the
specification.
"""
_sock = None
_auth_plugin_name = ''
_closed = False
_secure = False
def __init__(self, host=None, user=None, password="",
database=None, port=0, unix_socket=None,
charset='', sql_mode=None,
read_default_file=None, conv=None, use_unicode=None,
client_flag=0, cursorclass=Cursor, init_command=None,
connect_timeout=10, ssl=None, read_default_group=None,
compress=None, named_pipe=None,
autocommit=False, db=None, passwd=None, local_infile=False,
max_allowed_packet=16*1024*1024, defer_connect=False,
auth_plugin_map=None, read_timeout=None, write_timeout=None,
bind_address=None, binary_prefix=False, program_name=None,
server_public_key=None):
if use_unicode is None and sys.version_info[0] > 2:
use_unicode = True
if db is not None and database is None:
database = db
if passwd is not None and not password:
password = passwd
if compress or named_pipe:
raise NotImplementedError("compress and named_pipe arguments are not supported")
self._local_infile = bool(local_infile)
if self._local_infile:
client_flag |= CLIENT.LOCAL_FILES
if read_default_group and not read_default_file:
if sys.platform.startswith("win"):
read_default_file = "c:\\my.ini"
else:
read_default_file = "/etc/my.cnf"
if read_default_file:
if not read_default_group:
read_default_group = "client"
cfg = Parser()
cfg.read(os.path.expanduser(read_default_file))
def _config(key, arg):
if arg:
return arg
try:
return cfg.get(read_default_group, key)
except Exception:
return arg
user = _config("user", user)
password = _config("password", password)
host = _config("host", host)
database = _config("database", database)
unix_socket = _config("socket", unix_socket)
port = int(_config("port", port))
bind_address = _config("bind-address", bind_address)
charset = _config("default-character-set", charset)
if not ssl:
ssl = {}
if isinstance(ssl, dict):
for key in ["ca", "capath", "cert", "key", "cipher"]:
value = _config("ssl-" + key, ssl.get(key))
if value:
ssl[key] = value
self.ssl = False
if ssl:
if not SSL_ENABLED:
raise NotImplementedError("ssl module not found")
self.ssl = True
client_flag |= CLIENT.SSL
self.ctx = self._create_ssl_ctx(ssl)
self.host = host or "localhost"
self.port = port or 3306
self.user = user or DEFAULT_USER
self.password = password or b""
if isinstance(self.password, text_type):
self.password = self.password.encode('latin1')
self.db = database
self.unix_socket = unix_socket
self.bind_address = bind_address
if not (0 < connect_timeout <= 31536000):
raise ValueError("connect_timeout should be >0 and <=31536000")
self.connect_timeout = connect_timeout or None
if read_timeout is not None and read_timeout <= 0:
raise ValueError("read_timeout should be >= 0")
self._read_timeout = read_timeout
if write_timeout is not None and write_timeout <= 0:
raise ValueError("write_timeout should be >= 0")
self._write_timeout = write_timeout
if charset:
self.charset = charset
self.use_unicode = True
else:
self.charset = DEFAULT_CHARSET
self.use_unicode = False
if use_unicode is not None:
self.use_unicode = use_unicode
self.encoding = charset_by_name(self.charset).encoding
client_flag |= CLIENT.CAPABILITIES
if self.db:
client_flag |= CLIENT.CONNECT_WITH_DB
self.client_flag = client_flag
self.cursorclass = cursorclass
self._result = None
self._affected_rows = 0
self.host_info = "Not connected"
#: specified autocommit mode. None means use server default.
self.autocommit_mode = autocommit
if conv is None:
conv = converters.conversions
# Need for MySQLdb compatibility.
self.encoders = dict([(k, v) for (k, v) in conv.items() if type(k) is not int])
self.decoders = dict([(k, v) for (k, v) in conv.items() if type(k) is int])
self.sql_mode = sql_mode
self.init_command = init_command
self.max_allowed_packet = max_allowed_packet
self._auth_plugin_map = auth_plugin_map or {}
self._binary_prefix = binary_prefix
self.server_public_key = server_public_key
self._connect_attrs = {
'_client_name': 'pymysql',
'_pid': str(os.getpid()),
'_client_version': VERSION_STRING,
}
if program_name:
self._connect_attrs["program_name"] = program_name
elif sys.argv:
self._connect_attrs["program_name"] = sys.argv[0]
if defer_connect:
self._sock = None
else:
self.connect()
def _create_ssl_ctx(self, sslp):
if isinstance(sslp, ssl.SSLContext):
return sslp
ca = sslp.get('ca')
capath = sslp.get('capath')
hasnoca = ca is None and capath is None
ctx = ssl.create_default_context(cafile=ca, capath=capath)
ctx.check_hostname = not hasnoca and sslp.get('check_hostname', True)
ctx.verify_mode = ssl.CERT_NONE if hasnoca else ssl.CERT_REQUIRED
if 'cert' in sslp:
ctx.load_cert_chain(sslp['cert'], keyfile=sslp.get('key'))
if 'cipher' in sslp:
ctx.set_ciphers(sslp['cipher'])
ctx.options |= ssl.OP_NO_SSLv2
ctx.options |= ssl.OP_NO_SSLv3
return ctx
def close(self):
"""
Send the quit message and close the socket.
See `Connection.close() <https://www.python.org/dev/peps/pep-0249/#Connection.close>`_
in the specification.
:raise Error: If the connection is already closed.
"""
if self._closed:
raise err.Error("Already closed")
self._closed = True
if self._sock is None:
return
send_data = struct.pack('<iB', 1, COMMAND.COM_QUIT)
try:
self._write_bytes(send_data)
except Exception:
pass
finally:
self._force_close()
@property
def open(self):
"""Return True if the connection is open"""
return self._sock is not None
def _force_close(self):
"""Close connection without QUIT message"""
if self._sock:
try:
self._sock.close()
except: # noqa
pass
self._sock = None
self._rfile = None
__del__ = _force_close
def autocommit(self, value):
self.autocommit_mode = bool(value)
current = self.get_autocommit()
if value != current:
self._send_autocommit_mode()
def get_autocommit(self):
return bool(self.server_status &
SERVER_STATUS.SERVER_STATUS_AUTOCOMMIT)
def _read_ok_packet(self):
pkt = self._read_packet()
if not pkt.is_ok_packet():
raise err.OperationalError(2014, "Command Out of Sync")
ok = OKPacketWrapper(pkt)
self.server_status = ok.server_status
return ok
def _send_autocommit_mode(self):
"""Set whether or not to commit after every execute()"""
self._execute_command(COMMAND.COM_QUERY, "SET AUTOCOMMIT = %s" %
self.escape(self.autocommit_mode))
self._read_ok_packet()
def begin(self):
"""Begin transaction."""
self._execute_command(COMMAND.COM_QUERY, "BEGIN")
self._read_ok_packet()
def commit(self):
"""
Commit changes to stable storage.
See `Connection.commit() <https://www.python.org/dev/peps/pep-0249/#commit>`_
in the specification.
"""
self._execute_command(COMMAND.COM_QUERY, "COMMIT")
self._read_ok_packet()
def rollback(self):
"""
Roll back the current transaction.
See `Connection.rollback() <https://www.python.org/dev/peps/pep-0249/#rollback>`_
in the specification.
"""
self._execute_command(COMMAND.COM_QUERY, "ROLLBACK")
self._read_ok_packet()
def show_warnings(self):
"""Send the "SHOW WARNINGS" SQL command."""
self._execute_command(COMMAND.COM_QUERY, "SHOW WARNINGS")
result = MySQLResult(self)
result.read()
return result.rows
def select_db(self, db):
"""
Set current db.
:param db: The name of the db.
"""
self._execute_command(COMMAND.COM_INIT_DB, db)
self._read_ok_packet()
def escape(self, obj, mapping=None):
"""Escape whatever value you pass to it.
Non-standard, for internal use; do not use this in your applications.
"""
if isinstance(obj, str_type):
return "'" + self.escape_string(obj) + "'"
if isinstance(obj, (bytes, bytearray)):
ret = self._quote_bytes(obj)
if self._binary_prefix:
ret = "_binary" + ret
return ret
return converters.escape_item(obj, self.charset, mapping=mapping)
def literal(self, obj):
"""Alias for escape()
Non-standard, for internal use; do not use this in your applications.
"""
return self.escape(obj, self.encoders)
def escape_string(self, s):
if (self.server_status &
SERVER_STATUS.SERVER_STATUS_NO_BACKSLASH_ESCAPES):
return s.replace("'", "''")
return converters.escape_string(s)
def _quote_bytes(self, s):
if (self.server_status &
SERVER_STATUS.SERVER_STATUS_NO_BACKSLASH_ESCAPES):
return "'%s'" % (_fast_surrogateescape(s.replace(b"'", b"''")),)
return converters.escape_bytes(s)
def cursor(self, cursor=None):
"""
Create a new cursor to execute queries with.
:param cursor: The type of cursor to create; one of :py:class:`Cursor`,
:py:class:`SSCursor`, :py:class:`DictCursor`, or :py:class:`SSDictCursor`.
None means use Cursor.
"""
if cursor:
return cursor(self)
return self.cursorclass(self)
def __enter__(self):
"""Context manager that returns a Cursor"""
return self.cursor()
def __exit__(self, exc, value, traceback):
"""On successful exit, commit. On exception, rollback"""
if exc:
self.rollback()
else:
self.commit()
# The following methods are INTERNAL USE ONLY (called from Cursor)
def query(self, sql, unbuffered=False):
# if DEBUG:
# print("DEBUG: sending query:", sql)
if isinstance(sql, text_type) and not (JYTHON or IRONPYTHON):
if PY2:
sql = sql.encode(self.encoding)
else:
sql = sql.encode(self.encoding, 'surrogateescape')
self._execute_command(COMMAND.COM_QUERY, sql)
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
return self._affected_rows
def next_result(self, unbuffered=False):
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
return self._affected_rows
def affected_rows(self):
return self._affected_rows
def kill(self, thread_id):
arg = struct.pack('<I', thread_id)
self._execute_command(COMMAND.COM_PROCESS_KILL, arg)
return self._read_ok_packet()
def ping(self, reconnect=True):
"""
Check if the server is alive.
:param reconnect: If the connection is closed, reconnect.
:raise Error: If the connection is closed and reconnect=False.
"""
if self._sock is None:
if reconnect:
self.connect()
reconnect = False
else:
raise err.Error("Already closed")
try:
self._execute_command(COMMAND.COM_PING, "")
self._read_ok_packet()
except Exception:
if reconnect:
self.connect()
self.ping(False)
else:
raise
def set_charset(self, charset):
# Make sure charset is supported.
encoding = charset_by_name(charset).encoding
self._execute_command(COMMAND.COM_QUERY, "SET NAMES %s" % self.escape(charset))
self._read_packet()
self.charset = charset
self.encoding = encoding
def connect(self, sock=None):
self._closed = False
try:
if sock is None:
if self.unix_socket:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(self.connect_timeout)
sock.connect(self.unix_socket)
self.host_info = "Localhost via UNIX socket"
self._secure = True
if DEBUG: print('connected using unix_socket')
else:
kwargs = {}
if self.bind_address is not None:
kwargs['source_address'] = (self.bind_address, 0)
while True:
try:
sock = socket.create_connection(
(self.host, self.port), self.connect_timeout,
**kwargs)
break
except (OSError, IOError) as e:
if e.errno == errno.EINTR:
continue
raise
self.host_info = "socket %s:%d" % (self.host, self.port)
if DEBUG: print('connected using socket')
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.settimeout(None)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
self._sock = sock
self._rfile = _makefile(sock, 'rb')
self._next_seq_id = 0
self._get_server_information()
self._request_authentication()
if self.sql_mode is not None:
c = self.cursor()
c.execute("SET sql_mode=%s", (self.sql_mode,))
if self.init_command is not None:
c = self.cursor()
c.execute(self.init_command)
c.close()
self.commit()
if self.autocommit_mode is not None:
self.autocommit(self.autocommit_mode)
except BaseException as e:
self._rfile = None
if sock is not None:
try:
sock.close()
except: # noqa
pass
if isinstance(e, (OSError, IOError, socket.error)):
exc = err.OperationalError(
2003,
"Can't connect to MySQL server on %r (%s)" % (
self.host, e))
# Keep original exception and traceback to investigate error.
exc.original_exception = e
exc.traceback = traceback.format_exc()
if DEBUG: print(exc.traceback)
raise exc
# If e is neither DatabaseError or IOError, It's a bug.
# But raising AssertionError hides original error.
# So just reraise it.
raise
def write_packet(self, payload):
"""Writes an entire "mysql packet" in its entirety to the network
addings its length and sequence number.
"""
# Internal note: when you build packet manualy and calls _write_bytes()
# directly, you should set self._next_seq_id properly.
data = pack_int24(len(payload)) + int2byte(self._next_seq_id) + payload
if DEBUG: dump_packet(data)
self._write_bytes(data)
self._next_seq_id = (self._next_seq_id + 1) % 256
def _read_packet(self, packet_type=MysqlPacket):
"""Read an entire "mysql packet" in its entirety from the network
and return a MysqlPacket type that represents the results.
:raise OperationalError: If the connection to the MySQL server is lost.
:raise InternalError: If the packet sequence number is wrong.
"""
buff = b''
while True:
packet_header = self._read_bytes(4)
#if DEBUG: dump_packet(packet_header)
btrl, btrh, packet_number = struct.unpack('<HBB', packet_header)
bytes_to_read = btrl + (btrh << 16)
if packet_number != self._next_seq_id:
self._force_close()
if packet_number == 0:
# MariaDB sends error packet with seqno==0 when shutdown
raise err.OperationalError(
CR.CR_SERVER_LOST,
"Lost connection to MySQL server during query")
raise err.InternalError(
"Packet sequence number wrong - got %d expected %d"
% (packet_number, self._next_seq_id))
self._next_seq_id = (self._next_seq_id + 1) % 256
recv_data = self._read_bytes(bytes_to_read)
if DEBUG: dump_packet(recv_data)
buff += recv_data
# https://dev.mysql.com/doc/internals/en/sending-more-than-16mbyte.html
if bytes_to_read == 0xffffff:
continue
if bytes_to_read < MAX_PACKET_LEN:
break
packet = packet_type(buff, self.encoding)
packet.check_error()
return packet
def _read_bytes(self, num_bytes):
self._sock.settimeout(self._read_timeout)
while True:
try:
data = self._rfile.read(num_bytes)
break
except (IOError, OSError) as e:
if e.errno == errno.EINTR:
continue
self._force_close()
raise err.OperationalError(
CR.CR_SERVER_LOST,
"Lost connection to MySQL server during query (%s)" % (e,))
if len(data) < num_bytes:
self._force_close()
raise err.OperationalError(
CR.CR_SERVER_LOST, "Lost connection to MySQL server during query")
return data
def _write_bytes(self, data):
self._sock.settimeout(self._write_timeout)
try:
self._sock.sendall(data)
except IOError as e:
self._force_close()
raise err.OperationalError(
CR.CR_SERVER_GONE_ERROR,
"MySQL server has gone away (%r)" % (e,))
def _read_query_result(self, unbuffered=False):
self._result = None
if unbuffered:
try:
result = MySQLResult(self)
result.init_unbuffered_query()
except:
result.unbuffered_active = False
result.connection = None
raise
else:
result = MySQLResult(self)
result.read()
self._result = result
if result.server_status is not None:
self.server_status = result.server_status
return result.affected_rows
def insert_id(self):
if self._result:
return self._result.insert_id
else:
return 0
def _execute_command(self, command, sql):
"""
:raise InterfaceError: If the connection is closed.
:raise ValueError: If no username was specified.
"""
if not self._sock:
raise err.InterfaceError("(0, '')")
# If the last query was unbuffered, make sure it finishes before
# sending new commands
if self._result is not None:
if self._result.unbuffered_active:
warnings.warn("Previous unbuffered result was left incomplete")
self._result._finish_unbuffered_query()
while self._result.has_next:
self.next_result()
self._result = None
if isinstance(sql, text_type):
sql = sql.encode(self.encoding)
packet_size = min(MAX_PACKET_LEN, len(sql) + 1) # +1 is for command
# tiny optimization: build first packet manually instead of
# calling self..write_packet()
prelude = struct.pack('<iB', packet_size, command)
packet = prelude + sql[:packet_size-1]
self._write_bytes(packet)
if DEBUG: dump_packet(packet)
self._next_seq_id = 1
if packet_size < MAX_PACKET_LEN:
return
sql = sql[packet_size-1:]
while True:
packet_size = min(MAX_PACKET_LEN, len(sql))
self.write_packet(sql[:packet_size])
sql = sql[packet_size:]
if not sql and packet_size < MAX_PACKET_LEN:
break
def _request_authentication(self):
# https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::HandshakeResponse
if int(self.server_version.split('.', 1)[0]) >= 5:
self.client_flag |= CLIENT.MULTI_RESULTS
if self.user is None:
raise ValueError("Did not specify a username")
charset_id = charset_by_name(self.charset).id
if isinstance(self.user, text_type):
self.user = self.user.encode(self.encoding)
data_init = struct.pack('<iIB23s', self.client_flag, MAX_PACKET_LEN, charset_id, b'')
if self.ssl and self.server_capabilities & CLIENT.SSL:
self.write_packet(data_init)
self._sock = self.ctx.wrap_socket(self._sock, server_hostname=self.host)
self._rfile = _makefile(self._sock, 'rb')
self._secure = True
data = data_init + self.user + b'\0'
authresp = b''
plugin_name = None
if self._auth_plugin_name in ('', 'mysql_native_password'):
authresp = _auth.scramble_native_password(self.password, self.salt)
elif self._auth_plugin_name == 'caching_sha2_password':
plugin_name = b'caching_sha2_password'
if self.password:
if DEBUG:
print("caching_sha2: trying fast path")
authresp = _auth.scramble_caching_sha2(self.password, self.salt)
else:
if DEBUG:
print("caching_sha2: empty password")
elif self._auth_plugin_name == 'sha256_password':
plugin_name = b'sha256_password'
if self.ssl and self.server_capabilities & CLIENT.SSL:
authresp = self.password + b'\0'
elif self.password:
authresp = b'\1' # request public key
else:
authresp = b'\0' # empty password
if self.server_capabilities & CLIENT.PLUGIN_AUTH_LENENC_CLIENT_DATA:
data += lenenc_int(len(authresp)) + authresp
elif self.server_capabilities & CLIENT.SECURE_CONNECTION:
data += struct.pack('B', len(authresp)) + authresp
else: # pragma: no cover - not testing against servers without secure auth (>=5.0)
data += authresp + b'\0'
if self.db and self.server_capabilities & CLIENT.CONNECT_WITH_DB:
if isinstance(self.db, text_type):
self.db = self.db.encode(self.encoding)
data += self.db + b'\0'
if self.server_capabilities & CLIENT.PLUGIN_AUTH:
data += (plugin_name or b'') + b'\0'
if self.server_capabilities & CLIENT.CONNECT_ATTRS:
connect_attrs = b''
for k, v in self._connect_attrs.items():
k = k.encode('utf8')
connect_attrs += struct.pack('B', len(k)) + k
v = v.encode('utf8')
connect_attrs += struct.pack('B', len(v)) + v
data += struct.pack('B', len(connect_attrs)) + connect_attrs
self.write_packet(data)
auth_packet = self._read_packet()
# if authentication method isn't accepted the first byte
# will have the octet 254
if auth_packet.is_auth_switch_request():
if DEBUG: print("received auth switch")
# https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::AuthSwitchRequest
auth_packet.read_uint8() # 0xfe packet identifier
plugin_name = auth_packet.read_string()
if self.server_capabilities & CLIENT.PLUGIN_AUTH and plugin_name is not None:
auth_packet = self._process_auth(plugin_name, auth_packet)
else:
# send legacy handshake
data = _auth.scramble_old_password(self.password, self.salt) + b'\0'
self.write_packet(data)
auth_packet = self._read_packet()
elif auth_packet.is_extra_auth_data():
if DEBUG:
print("received extra data")
# https://dev.mysql.com/doc/internals/en/successful-authentication.html
if self._auth_plugin_name == "caching_sha2_password":
auth_packet = _auth.caching_sha2_password_auth(self, auth_packet)
elif self._auth_plugin_name == "sha256_password":
auth_packet = _auth.sha256_password_auth(self, auth_packet)
else:
raise err.OperationalError("Received extra packet for auth method %r", self._auth_plugin_name)
if DEBUG: print("Succeed to auth")
def _process_auth(self, plugin_name, auth_packet):
handler = self._get_auth_plugin_handler(plugin_name)
if handler:
try:
return handler.authenticate(auth_packet)
except AttributeError:
if plugin_name != b'dialog':
raise err.OperationalError(2059, "Authentication plugin '%s'"
" not loaded: - %r missing authenticate method" % (plugin_name, type(handler)))
if plugin_name == b"caching_sha2_password":
return _auth.caching_sha2_password_auth(self, auth_packet)
elif plugin_name == b"sha256_password":
return _auth.sha256_password_auth(self, auth_packet)
elif plugin_name == b"mysql_native_password":
data = _auth.scramble_native_password(self.password, auth_packet.read_all())
elif plugin_name == b"mysql_old_password":
data = _auth.scramble_old_password(self.password, auth_packet.read_all()) + b'\0'
elif plugin_name == b"mysql_clear_password":
# https://dev.mysql.com/doc/internals/en/clear-text-authentication.html
data = self.password + b'\0'
elif plugin_name == b"dialog":
pkt = auth_packet
while True:
flag = pkt.read_uint8()
echo = (flag & 0x06) == 0x02
last = (flag & 0x01) == 0x01
prompt = pkt.read_all()
if prompt == b"Password: ":
self.write_packet(self.password + b'\0')
elif handler:
resp = 'no response - TypeError within plugin.prompt method'
try:
resp = handler.prompt(echo, prompt)
self.write_packet(resp + b'\0')
except AttributeError:
raise err.OperationalError(2059, "Authentication plugin '%s'" \
" not loaded: - %r missing prompt method" % (plugin_name, handler))
except TypeError:
raise err.OperationalError(2061, "Authentication plugin '%s'" \
" %r didn't respond with string. Returned '%r' to prompt %r" % (plugin_name, handler, resp, prompt))
else:
raise err.OperationalError(2059, "Authentication plugin '%s' (%r) not configured" % (plugin_name, handler))
pkt = self._read_packet()
pkt.check_error()
if pkt.is_ok_packet() or last:
break
return pkt
else:
raise err.OperationalError(2059, "Authentication plugin '%s' not configured" % plugin_name)
self.write_packet(data)
pkt = self._read_packet()
pkt.check_error()
return pkt
def _get_auth_plugin_handler(self, plugin_name):
plugin_class = self._auth_plugin_map.get(plugin_name)
if not plugin_class and isinstance(plugin_name, bytes):
plugin_class = self._auth_plugin_map.get(plugin_name.decode('ascii'))
if plugin_class:
try:
handler = plugin_class(self)
except TypeError:
raise err.OperationalError(2059, "Authentication plugin '%s'"
" not loaded: - %r cannot be constructed with connection object" % (plugin_name, plugin_class))
else:
handler = None
return handler
# _mysql support
def thread_id(self):
return self.server_thread_id[0]
def character_set_name(self):
return self.charset
def get_host_info(self):
return self.host_info
def get_proto_info(self):
return self.protocol_version
def _get_server_information(self):
i = 0
packet = self._read_packet()
data = packet.get_all_data()
self.protocol_version = byte2int(data[i:i+1])
i += 1
server_end = data.find(b'\0', i)
self.server_version = data[i:server_end].decode('latin1')
i = server_end + 1
self.server_thread_id = struct.unpack('<I', data[i:i+4])
i += 4
self.salt = data[i:i+8]
i += 9 # 8 + 1(filler)
self.server_capabilities = struct.unpack('<H', data[i:i+2])[0]
i += 2
if len(data) >= i + 6:
lang, stat, cap_h, salt_len = struct.unpack('<BHHB', data[i:i+6])
i += 6
# TODO: deprecate server_language and server_charset.
# mysqlclient-python doesn't provide it.
self.server_language = lang
try:
self.server_charset = charset_by_id(lang).name
except KeyError:
# unknown collation
self.server_charset = None
self.server_status = stat
if DEBUG: print("server_status: %x" % stat)
self.server_capabilities |= cap_h << 16
if DEBUG: print("salt_len:", salt_len)
salt_len = max(12, salt_len - 9)
# reserved
i += 10
if len(data) >= i + salt_len:
# salt_len includes auth_plugin_data_part_1 and filler
self.salt += data[i:i+salt_len]
i += salt_len
i+=1
# AUTH PLUGIN NAME may appear here.
if self.server_capabilities & CLIENT.PLUGIN_AUTH and len(data) >= i:
# Due to Bug#59453 the auth-plugin-name is missing the terminating
# NUL-char in versions prior to 5.5.10 and 5.6.2.
# ref: https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::Handshake
# didn't use version checks as mariadb is corrected and reports
# earlier than those two.
server_end = data.find(b'\0', i)
if server_end < 0: # pragma: no cover - very specific upstream bug
# not found \0 and last field so take it all
self._auth_plugin_name = data[i:].decode('utf-8')
else:
self._auth_plugin_name = data[i:server_end].decode('utf-8')
def get_server_info(self):
return self.server_version
Warning = err.Warning
Error = err.Error
InterfaceError = err.InterfaceError
DatabaseError = err.DatabaseError
DataError = err.DataError
OperationalError = err.OperationalError
IntegrityError = err.IntegrityError
InternalError = err.InternalError
ProgrammingError = err.ProgrammingError
NotSupportedError = err.NotSupportedError
class MySQLResult(object):
def __init__(self, connection):
"""
:type connection: Connection
"""
self.connection = connection
self.affected_rows = None
self.insert_id = None
self.server_status = None
self.warning_count = 0
self.message = None
self.field_count = 0
self.description = None
self.rows = None
self.has_next = None
self.unbuffered_active = False
def __del__(self):
if self.unbuffered_active:
self._finish_unbuffered_query()
def read(self):
try:
first_packet = self.connection._read_packet()
if first_packet.is_ok_packet():
self._read_ok_packet(first_packet)
elif first_packet.is_load_local_packet():
self._read_load_local_packet(first_packet)
else:
self._read_result_packet(first_packet)
finally:
self.connection = None
def init_unbuffered_query(self):
"""
:raise OperationalError: If the connection to the MySQL server is lost.
:raise InternalError:
"""
self.unbuffered_active = True
first_packet = self.connection._read_packet()
if first_packet.is_ok_packet():
self._read_ok_packet(first_packet)
self.unbuffered_active = False
self.connection = None
elif first_packet.is_load_local_packet():
self._read_load_local_packet(first_packet)
self.unbuffered_active = False
self.connection = None
else:
self.field_count = first_packet.read_length_encoded_integer()
self._get_descriptions()
# Apparently, MySQLdb picks this number because it's the maximum
# value of a 64bit unsigned integer. Since we're emulating MySQLdb,
# we set it to this instead of None, which would be preferred.
self.affected_rows = 18446744073709551615
def _read_ok_packet(self, first_packet):
ok_packet = OKPacketWrapper(first_packet)
self.affected_rows = ok_packet.affected_rows
self.insert_id = ok_packet.insert_id
self.server_status = ok_packet.server_status
self.warning_count = ok_packet.warning_count
self.message = ok_packet.message
self.has_next = ok_packet.has_next
def _read_load_local_packet(self, first_packet):
if not self.connection._local_infile:
raise RuntimeError(
"**WARN**: Received LOAD_LOCAL packet but local_infile option is false.")
load_packet = LoadLocalPacketWrapper(first_packet)
sender = LoadLocalFile(load_packet.filename, self.connection)
try:
sender.send_data()
except:
self.connection._read_packet() # skip ok packet
raise
ok_packet = self.connection._read_packet()
if not ok_packet.is_ok_packet(): # pragma: no cover - upstream induced protocol error
raise err.OperationalError(2014, "Commands Out of Sync")
self._read_ok_packet(ok_packet)
def _check_packet_is_eof(self, packet):
if not packet.is_eof_packet():
return False
#TODO: Support CLIENT.DEPRECATE_EOF
# 1) Add DEPRECATE_EOF to CAPABILITIES
# 2) Mask CAPABILITIES with server_capabilities
# 3) if server_capabilities & CLIENT.DEPRECATE_EOF: use OKPacketWrapper instead of EOFPacketWrapper
wp = EOFPacketWrapper(packet)
self.warning_count = wp.warning_count
self.has_next = wp.has_next
return True
def _read_result_packet(self, first_packet):
self.field_count = first_packet.read_length_encoded_integer()
self._get_descriptions()
self._read_rowdata_packet()
def _read_rowdata_packet_unbuffered(self):
# Check if in an active query
if not self.unbuffered_active:
return
# EOF
packet = self.connection._read_packet()
if self._check_packet_is_eof(packet):
self.unbuffered_active = False
self.connection = None
self.rows = None
return
row = self._read_row_from_packet(packet)
self.affected_rows = 1
self.rows = (row,) # rows should tuple of row for MySQL-python compatibility.
return row
def _finish_unbuffered_query(self):
# After much reading on the MySQL protocol, it appears that there is,
# in fact, no way to stop MySQL from sending all the data after
# executing a query, so we just spin, and wait for an EOF packet.
while self.unbuffered_active:
packet = self.connection._read_packet()
if self._check_packet_is_eof(packet):
self.unbuffered_active = False
self.connection = None # release reference to kill cyclic reference.
def _read_rowdata_packet(self):
"""Read a rowdata packet for each data row in the result set."""
rows = []
while True:
packet = self.connection._read_packet()
if self._check_packet_is_eof(packet):
self.connection = None # release reference to kill cyclic reference.
break
rows.append(self._read_row_from_packet(packet))
self.affected_rows = len(rows)
self.rows = tuple(rows)
def _read_row_from_packet(self, packet):
row = []
for encoding, converter in self.converters:
try:
data = packet.read_length_coded_string()
except IndexError:
# No more columns in this row
# See https://github.com/PyMySQL/PyMySQL/pull/434
break
if data is not None:
if encoding is not None:
data = data.decode(encoding)
if DEBUG: print("DEBUG: DATA = ", data)
if converter is not None:
data = converter(data)
row.append(data)
return tuple(row)
def _get_descriptions(self):
"""Read a column descriptor packet for each column in the result."""
self.fields = []
self.converters = []
use_unicode = self.connection.use_unicode
conn_encoding = self.connection.encoding
description = []
for i in range_type(self.field_count):
field = self.connection._read_packet(FieldDescriptorPacket)
self.fields.append(field)
description.append(field.description())
field_type = field.type_code
if use_unicode:
if field_type == FIELD_TYPE.JSON:
# When SELECT from JSON column: charset = binary
# When SELECT CAST(... AS JSON): charset = connection encoding
# This behavior is different from TEXT / BLOB.
# We should decode result by connection encoding regardless charsetnr.
# See https://github.com/PyMySQL/PyMySQL/issues/488
encoding = conn_encoding # SELECT CAST(... AS JSON)
elif field_type in TEXT_TYPES:
if field.charsetnr == 63: # binary
# TEXTs with charset=binary means BINARY types.
encoding = None
else:
encoding = conn_encoding
else:
# Integers, Dates and Times, and other basic data is encoded in ascii
encoding = 'ascii'
else:
encoding = None
converter = self.connection.decoders.get(field_type)
if converter is converters.through:
converter = None
if DEBUG: print("DEBUG: field={}, converter={}".format(field, converter))
self.converters.append((encoding, converter))
eof_packet = self.connection._read_packet()
assert eof_packet.is_eof_packet(), 'Protocol error, expecting EOF'
self.description = tuple(description)
class LoadLocalFile(object):
def __init__(self, filename, connection):
self.filename = filename
self.connection = connection
def send_data(self):
"""Send data packets from the local file to the server"""
if not self.connection._sock:
raise err.InterfaceError("(0, '')")
conn = self.connection
try:
with open(self.filename, 'rb') as open_file:
packet_size = min(conn.max_allowed_packet, 16*1024) # 16KB is efficient enough
while True:
chunk = open_file.read(packet_size)
if not chunk:
break
conn.write_packet(chunk)
except IOError:
raise err.OperationalError(1017, "Can't find file '{0}'".format(self.filename))
finally:
# send the empty packet to signify we are done sending data
conn.write_packet(b'') | ytp1 | /ytp1-6.3.12-cp36-cp36m-win_amd64.whl/pymysql/connections.py | connections.py |
from __future__ import print_function
from .charset import MBLENGTH
from ._compat import PY2, range_type
from . import FIELD_TYPE, SERVER_STATUS
from . import err
from .util import byte2int
import struct
import sys
DEBUG = False
NULL_COLUMN = 251
UNSIGNED_CHAR_COLUMN = 251
UNSIGNED_SHORT_COLUMN = 252
UNSIGNED_INT24_COLUMN = 253
UNSIGNED_INT64_COLUMN = 254
def dump_packet(data): # pragma: no cover
def printable(data):
if 32 <= byte2int(data) < 127:
if isinstance(data, int):
return chr(data)
return data
return '.'
try:
print("packet length:", len(data))
for i in range(1, 7):
f = sys._getframe(i)
print("call[%d]: %s (line %d)" % (i, f.f_code.co_name, f.f_lineno))
print("-" * 66)
except ValueError:
pass
dump_data = [data[i:i+16] for i in range_type(0, min(len(data), 256), 16)]
for d in dump_data:
print(' '.join("{:02X}".format(byte2int(x)) for x in d) +
' ' * (16 - len(d)) + ' ' * 2 +
''.join(printable(x) for x in d))
print("-" * 66)
print()
class MysqlPacket(object):
"""Representation of a MySQL response packet.
Provides an interface for reading/parsing the packet results.
"""
__slots__ = ('_position', '_data')
def __init__(self, data, encoding):
self._position = 0
self._data = data
def get_all_data(self):
return self._data
def read(self, size):
"""Read the first 'size' bytes in packet and advance cursor past them."""
result = self._data[self._position:(self._position+size)]
if len(result) != size:
error = ('Result length not requested length:\n'
'Expected=%s. Actual=%s. Position: %s. Data Length: %s'
% (size, len(result), self._position, len(self._data)))
if DEBUG:
print(error)
self.dump()
raise AssertionError(error)
self._position += size
return result
def read_all(self):
"""Read all remaining data in the packet.
(Subsequent read() will return errors.)
"""
result = self._data[self._position:]
self._position = None # ensure no subsequent read()
return result
def advance(self, length):
"""Advance the cursor in data buffer 'length' bytes."""
new_position = self._position + length
if new_position < 0 or new_position > len(self._data):
raise Exception('Invalid advance amount (%s) for cursor. '
'Position=%s' % (length, new_position))
self._position = new_position
def rewind(self, position=0):
"""Set the position of the data buffer cursor to 'position'."""
if position < 0 or position > len(self._data):
raise Exception("Invalid position to rewind cursor to: %s." % position)
self._position = position
def get_bytes(self, position, length=1):
"""Get 'length' bytes starting at 'position'.
Position is start of payload (first four packet header bytes are not
included) starting at index '0'.
No error checking is done. If requesting outside end of buffer
an empty string (or string shorter than 'length') may be returned!
"""
return self._data[position:(position+length)]
if PY2:
def read_uint8(self):
result = ord(self._data[self._position])
self._position += 1
return result
else:
def read_uint8(self):
result = self._data[self._position]
self._position += 1
return result
def read_uint16(self):
result = struct.unpack_from('<H', self._data, self._position)[0]
self._position += 2
return result
def read_uint24(self):
low, high = struct.unpack_from('<HB', self._data, self._position)
self._position += 3
return low + (high << 16)
def read_uint32(self):
result = struct.unpack_from('<I', self._data, self._position)[0]
self._position += 4
return result
def read_uint64(self):
result = struct.unpack_from('<Q', self._data, self._position)[0]
self._position += 8
return result
def read_string(self):
end_pos = self._data.find(b'\0', self._position)
if end_pos < 0:
return None
result = self._data[self._position:end_pos]
self._position = end_pos + 1
return result
def read_length_encoded_integer(self):
"""Read a 'Length Coded Binary' number from the data buffer.
Length coded numbers can be anywhere from 1 to 9 bytes depending
on the value of the first byte.
"""
c = self.read_uint8()
if c == NULL_COLUMN:
return None
if c < UNSIGNED_CHAR_COLUMN:
return c
elif c == UNSIGNED_SHORT_COLUMN:
return self.read_uint16()
elif c == UNSIGNED_INT24_COLUMN:
return self.read_uint24()
elif c == UNSIGNED_INT64_COLUMN:
return self.read_uint64()
def read_length_coded_string(self):
"""Read a 'Length Coded String' from the data buffer.
A 'Length Coded String' consists first of a length coded
(unsigned, positive) integer represented in 1-9 bytes followed by
that many bytes of binary data. (For example "cat" would be "3cat".)
"""
length = self.read_length_encoded_integer()
if length is None:
return None
return self.read(length)
def read_struct(self, fmt):
s = struct.Struct(fmt)
result = s.unpack_from(self._data, self._position)
self._position += s.size
return result
def is_ok_packet(self):
# https://dev.mysql.com/doc/internals/en/packet-OK_Packet.html
return self._data[0:1] == b'\0' and len(self._data) >= 7
def is_eof_packet(self):
# http://dev.mysql.com/doc/internals/en/generic-response-packets.html#packet-EOF_Packet
# Caution: \xFE may be LengthEncodedInteger.
# If \xFE is LengthEncodedInteger header, 8bytes followed.
return self._data[0:1] == b'\xfe' and len(self._data) < 9
def is_auth_switch_request(self):
# http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::AuthSwitchRequest
return self._data[0:1] == b'\xfe'
def is_extra_auth_data(self):
# https://dev.mysql.com/doc/internals/en/successful-authentication.html
return self._data[0:1] == b'\x01'
def is_resultset_packet(self):
field_count = ord(self._data[0:1])
return 1 <= field_count <= 250
def is_load_local_packet(self):
return self._data[0:1] == b'\xfb'
def is_error_packet(self):
return self._data[0:1] == b'\xff'
def check_error(self):
if self.is_error_packet():
self.rewind()
self.advance(1) # field_count == error (we already know that)
errno = self.read_uint16()
if DEBUG: print("errno =", errno)
err.raise_mysql_exception(self._data)
def dump(self):
dump_packet(self._data)
class FieldDescriptorPacket(MysqlPacket):
"""A MysqlPacket that represents a specific column's metadata in the result.
Parsing is automatically done and the results are exported via public
attributes on the class such as: db, table_name, name, length, type_code.
"""
def __init__(self, data, encoding):
MysqlPacket.__init__(self, data, encoding)
self._parse_field_descriptor(encoding)
def _parse_field_descriptor(self, encoding):
"""Parse the 'Field Descriptor' (Metadata) packet.
This is compatible with MySQL 4.1+ (not compatible with MySQL 4.0).
"""
self.catalog = self.read_length_coded_string()
self.db = self.read_length_coded_string()
self.table_name = self.read_length_coded_string().decode(encoding)
self.org_table = self.read_length_coded_string().decode(encoding)
self.name = self.read_length_coded_string().decode(encoding)
self.org_name = self.read_length_coded_string().decode(encoding)
self.charsetnr, self.length, self.type_code, self.flags, self.scale = (
self.read_struct('<xHIBHBxx'))
# 'default' is a length coded binary and is still in the buffer?
# not used for normal result sets...
def description(self):
"""Provides a 7-item tuple compatible with the Python PEP249 DB Spec."""
return (
self.name,
self.type_code,
None, # TODO: display_length; should this be self.length?
self.get_column_length(), # 'internal_size'
self.get_column_length(), # 'precision' # TODO: why!?!?
self.scale,
self.flags % 2 == 0)
def get_column_length(self):
if self.type_code == FIELD_TYPE.VAR_STRING:
mblen = MBLENGTH.get(self.charsetnr, 1)
return self.length // mblen
return self.length
def __str__(self):
return ('%s %r.%r.%r, type=%s, flags=%x'
% (self.__class__, self.db, self.table_name, self.name,
self.type_code, self.flags))
class OKPacketWrapper(object):
"""
OK Packet Wrapper. It uses an existing packet object, and wraps
around it, exposing useful variables while still providing access
to the original packet objects variables and methods.
"""
def __init__(self, from_packet):
if not from_packet.is_ok_packet():
raise ValueError('Cannot create ' + str(self.__class__.__name__) +
' object from invalid packet type')
self.packet = from_packet
self.packet.advance(1)
self.affected_rows = self.packet.read_length_encoded_integer()
self.insert_id = self.packet.read_length_encoded_integer()
self.server_status, self.warning_count = self.read_struct('<HH')
self.message = self.packet.read_all()
self.has_next = self.server_status & SERVER_STATUS.SERVER_MORE_RESULTS_EXISTS
def __getattr__(self, key):
return getattr(self.packet, key)
class EOFPacketWrapper(object):
"""
EOF Packet Wrapper. It uses an existing packet object, and wraps
around it, exposing useful variables while still providing access
to the original packet objects variables and methods.
"""
def __init__(self, from_packet):
if not from_packet.is_eof_packet():
raise ValueError(
"Cannot create '{0}' object from invalid packet type".format(
self.__class__))
self.packet = from_packet
self.warning_count, self.server_status = self.packet.read_struct('<xhh')
if DEBUG: print("server_status=", self.server_status)
self.has_next = self.server_status & SERVER_STATUS.SERVER_MORE_RESULTS_EXISTS
def __getattr__(self, key):
return getattr(self.packet, key)
class LoadLocalPacketWrapper(object):
"""
Load Local Packet Wrapper. It uses an existing packet object, and wraps
around it, exposing useful variables while still providing access
to the original packet objects variables and methods.
"""
def __init__(self, from_packet):
if not from_packet.is_load_local_packet():
raise ValueError(
"Cannot create '{0}' object from invalid packet type".format(
self.__class__))
self.packet = from_packet
self.filename = self.packet.get_all_data()[1:]
if DEBUG: print("filename=", self.filename)
def __getattr__(self, key):
return getattr(self.packet, key) | ytp1 | /ytp1-6.3.12-cp36-cp36m-win_amd64.whl/pymysql/protocol.py | protocol.py |
import sys
from ._compat import PY2
from . import FIELD_TYPE
from .converters import escape_dict, escape_sequence, escape_string
from .err import (
Warning, Error, InterfaceError, DataError,
DatabaseError, OperationalError, IntegrityError, InternalError,
NotSupportedError, ProgrammingError, MySQLError)
from .times import (
Date, Time, Timestamp,
DateFromTicks, TimeFromTicks, TimestampFromTicks)
VERSION = (0, 9, 2, None)
if VERSION[3] is not None:
VERSION_STRING = "%d.%d.%d_%s" % VERSION
else:
VERSION_STRING = "%d.%d.%d" % VERSION[:3]
threadsafety = 1
apilevel = "2.0"
paramstyle = "pyformat"
class DBAPISet(frozenset):
def __ne__(self, other):
if isinstance(other, set):
return frozenset.__ne__(self, other)
else:
return other not in self
def __eq__(self, other):
if isinstance(other, frozenset):
return frozenset.__eq__(self, other)
else:
return other in self
def __hash__(self):
return frozenset.__hash__(self)
STRING = DBAPISet([FIELD_TYPE.ENUM, FIELD_TYPE.STRING,
FIELD_TYPE.VAR_STRING])
BINARY = DBAPISet([FIELD_TYPE.BLOB, FIELD_TYPE.LONG_BLOB,
FIELD_TYPE.MEDIUM_BLOB, FIELD_TYPE.TINY_BLOB])
NUMBER = DBAPISet([FIELD_TYPE.DECIMAL, FIELD_TYPE.DOUBLE, FIELD_TYPE.FLOAT,
FIELD_TYPE.INT24, FIELD_TYPE.LONG, FIELD_TYPE.LONGLONG,
FIELD_TYPE.TINY, FIELD_TYPE.YEAR])
DATE = DBAPISet([FIELD_TYPE.DATE, FIELD_TYPE.NEWDATE])
TIME = DBAPISet([FIELD_TYPE.TIME])
TIMESTAMP = DBAPISet([FIELD_TYPE.TIMESTAMP, FIELD_TYPE.DATETIME])
DATETIME = TIMESTAMP
ROWID = DBAPISet()
def Binary(x):
"""Return x as a binary type."""
if PY2:
return bytearray(x)
else:
return bytes(x)
def Connect(*args, **kwargs):
"""
Connect to the database; see connections.Connection.__init__() for
more information.
"""
from .connections import Connection
return Connection(*args, **kwargs)
from . import connections as _orig_conn
if _orig_conn.Connection.__init__.__doc__ is not None:
Connect.__doc__ = _orig_conn.Connection.__init__.__doc__
del _orig_conn
def get_client_info(): # for MySQLdb compatibility
version = VERSION
if VERSION[3] is None:
version = VERSION[:3]
return '.'.join(map(str, version))
connect = Connection = Connect
# we include a doctored version_info here for MySQLdb compatibility
version_info = (1, 3, 12, "final", 0)
NULL = "NULL"
__version__ = get_client_info()
def thread_safe():
return True # match MySQLdb.thread_safe()
def install_as_MySQLdb():
"""
After this function is called, any application that imports MySQLdb or
_mysql will unwittingly actually use pymysql.
"""
sys.modules["MySQLdb"] = sys.modules["_mysql"] = sys.modules["pymysql"]
__all__ = [
'BINARY', 'Binary', 'Connect', 'Connection', 'DATE', 'Date',
'Time', 'Timestamp', 'DateFromTicks', 'TimeFromTicks', 'TimestampFromTicks',
'DataError', 'DatabaseError', 'Error', 'FIELD_TYPE', 'IntegrityError',
'InterfaceError', 'InternalError', 'MySQLError', 'NULL', 'NUMBER',
'NotSupportedError', 'DBAPISet', 'OperationalError', 'ProgrammingError',
'ROWID', 'STRING', 'TIME', 'TIMESTAMP', 'Warning', 'apilevel', 'connect',
'connections', 'converters', 'cursors',
'escape_dict', 'escape_sequence', 'escape_string', 'get_client_info',
'paramstyle', 'threadsafety', 'version_info',
"install_as_MySQLdb",
"NULL", "__version__",
] | ytp1 | /ytp1-6.3.12-cp36-cp36m-win_amd64.whl/pymysql/__init__.py | __init__.py |
from socket import *
import io
import errno
__all__ = ['SocketIO']
EINTR = errno.EINTR
_blocking_errnos = (errno.EAGAIN, errno.EWOULDBLOCK)
class SocketIO(io.RawIOBase):
"""Raw I/O implementation for stream sockets.
This class supports the makefile() method on sockets. It provides
the raw I/O interface on top of a socket object.
"""
# One might wonder why not let FileIO do the job instead. There are two
# main reasons why FileIO is not adapted:
# - it wouldn't work under Windows (where you can't used read() and
# write() on a socket handle)
# - it wouldn't work with socket timeouts (FileIO would ignore the
# timeout and consider the socket non-blocking)
# XXX More docs
def __init__(self, sock, mode):
if mode not in ("r", "w", "rw", "rb", "wb", "rwb"):
raise ValueError("invalid mode: %r" % mode)
io.RawIOBase.__init__(self)
self._sock = sock
if "b" not in mode:
mode += "b"
self._mode = mode
self._reading = "r" in mode
self._writing = "w" in mode
self._timeout_occurred = False
def readinto(self, b):
"""Read up to len(b) bytes into the writable buffer *b* and return
the number of bytes read. If the socket is non-blocking and no bytes
are available, None is returned.
If *b* is non-empty, a 0 return value indicates that the connection
was shutdown at the other end.
"""
self._checkClosed()
self._checkReadable()
if self._timeout_occurred:
raise IOError("cannot read from timed out object")
while True:
try:
return self._sock.recv_into(b)
except timeout:
self._timeout_occurred = True
raise
except error as e:
n = e.args[0]
if n == EINTR:
continue
if n in _blocking_errnos:
return None
raise
def write(self, b):
"""Write the given bytes or bytearray object *b* to the socket
and return the number of bytes written. This can be less than
len(b) if not all data could be written. If the socket is
non-blocking and no bytes could be written None is returned.
"""
self._checkClosed()
self._checkWritable()
try:
return self._sock.send(b)
except error as e:
# XXX what about EINTR?
if e.args[0] in _blocking_errnos:
return None
raise
def readable(self):
"""True if the SocketIO is open for reading.
"""
if self.closed:
raise ValueError("I/O operation on closed socket.")
return self._reading
def writable(self):
"""True if the SocketIO is open for writing.
"""
if self.closed:
raise ValueError("I/O operation on closed socket.")
return self._writing
def seekable(self):
"""True if the SocketIO is open for seeking.
"""
if self.closed:
raise ValueError("I/O operation on closed socket.")
return super().seekable()
def fileno(self):
"""Return the file descriptor of the underlying socket.
"""
self._checkClosed()
return self._sock.fileno()
@property
def name(self):
if not self.closed:
return self.fileno()
else:
return -1
@property
def mode(self):
return self._mode
def close(self):
"""Close the SocketIO object. This doesn't close the underlying
socket, except if all references to it have disappeared.
"""
if self.closed:
return
io.RawIOBase.close(self)
self._sock._decref_socketios()
self._sock = None | ytp1 | /ytp1-6.3.12-cp36-cp36m-win_amd64.whl/pymysql/_socketio.py | _socketio.py |
import ctypes
from ptp.py_base import Base
class DisseminationField(Base):
"""信息分发"""
_fields_ = [
('SequenceSeries',ctypes.c_short)# ///序列系列号
,('SequenceNo',ctypes.c_int)# 序列号
]
def __init__(self,SequenceSeries= 0,SequenceNo=0):
super(DisseminationField,self).__init__()
self.SequenceSeries=int(SequenceSeries)
self.SequenceNo=int(SequenceNo)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.SequenceSeries=int(i_tuple[1])
self.SequenceNo=int(i_tuple[2])
class ReqUserLoginField(Base):
"""用户登录请求"""
_fields_ = [
('TradingDay',ctypes.c_char*9)# ///交易日
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('Password',ctypes.c_char*41)# 密码
,('UserProductInfo',ctypes.c_char*11)# 用户端产品信息
,('InterfaceProductInfo',ctypes.c_char*11)# 接口端产品信息
,('ProtocolInfo',ctypes.c_char*11)# 协议信息
,('MacAddress',ctypes.c_char*21)# Mac地址
,('OneTimePassword',ctypes.c_char*41)# 动态密码
,('ClientIPAddress',ctypes.c_char*16)# 终端IP地址
,('LoginRemark',ctypes.c_char*36)# 登录备注
]
def __init__(self,TradingDay= '',BrokerID='',UserID='',Password='',UserProductInfo='',InterfaceProductInfo='',ProtocolInfo='',MacAddress='',OneTimePassword='',ClientIPAddress='',LoginRemark=''):
super(ReqUserLoginField,self).__init__()
self.TradingDay=self._to_bytes(TradingDay)
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.Password=self._to_bytes(Password)
self.UserProductInfo=self._to_bytes(UserProductInfo)
self.InterfaceProductInfo=self._to_bytes(InterfaceProductInfo)
self.ProtocolInfo=self._to_bytes(ProtocolInfo)
self.MacAddress=self._to_bytes(MacAddress)
self.OneTimePassword=self._to_bytes(OneTimePassword)
self.ClientIPAddress=self._to_bytes(ClientIPAddress)
self.LoginRemark=self._to_bytes(LoginRemark)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradingDay=self._to_bytes(i_tuple[1])
self.BrokerID=self._to_bytes(i_tuple[2])
self.UserID=self._to_bytes(i_tuple[3])
self.Password=self._to_bytes(i_tuple[4])
self.UserProductInfo=self._to_bytes(i_tuple[5])
self.InterfaceProductInfo=self._to_bytes(i_tuple[6])
self.ProtocolInfo=self._to_bytes(i_tuple[7])
self.MacAddress=self._to_bytes(i_tuple[8])
self.OneTimePassword=self._to_bytes(i_tuple[9])
self.ClientIPAddress=self._to_bytes(i_tuple[10])
self.LoginRemark=self._to_bytes(i_tuple[11])
class RspUserLoginField(Base):
"""用户登录应答"""
_fields_ = [
('TradingDay',ctypes.c_char*9)# ///交易日
,('LoginTime',ctypes.c_char*9)# 登录成功时间
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('SystemName',ctypes.c_char*41)# 交易系统名称
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('MaxOrderRef',ctypes.c_char*13)# 最大报单引用
,('SHFETime',ctypes.c_char*9)# 上期所时间
,('DCETime',ctypes.c_char*9)# 大商所时间
,('CZCETime',ctypes.c_char*9)# 郑商所时间
,('FFEXTime',ctypes.c_char*9)# 中金所时间
,('INETime',ctypes.c_char*9)# 能源中心时间
]
def __init__(self,TradingDay= '',LoginTime='',BrokerID='',UserID='',SystemName='',FrontID=0,SessionID=0,MaxOrderRef='',SHFETime='',DCETime='',CZCETime='',FFEXTime='',INETime=''):
super(RspUserLoginField,self).__init__()
self.TradingDay=self._to_bytes(TradingDay)
self.LoginTime=self._to_bytes(LoginTime)
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.SystemName=self._to_bytes(SystemName)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.MaxOrderRef=self._to_bytes(MaxOrderRef)
self.SHFETime=self._to_bytes(SHFETime)
self.DCETime=self._to_bytes(DCETime)
self.CZCETime=self._to_bytes(CZCETime)
self.FFEXTime=self._to_bytes(FFEXTime)
self.INETime=self._to_bytes(INETime)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradingDay=self._to_bytes(i_tuple[1])
self.LoginTime=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.UserID=self._to_bytes(i_tuple[4])
self.SystemName=self._to_bytes(i_tuple[5])
self.FrontID=int(i_tuple[6])
self.SessionID=int(i_tuple[7])
self.MaxOrderRef=self._to_bytes(i_tuple[8])
self.SHFETime=self._to_bytes(i_tuple[9])
self.DCETime=self._to_bytes(i_tuple[10])
self.CZCETime=self._to_bytes(i_tuple[11])
self.FFEXTime=self._to_bytes(i_tuple[12])
self.INETime=self._to_bytes(i_tuple[13])
class UserLogoutField(Base):
"""用户登出请求"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
]
def __init__(self,BrokerID= '',UserID=''):
super(UserLogoutField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
class ForceUserLogoutField(Base):
"""强制交易员退出"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
]
def __init__(self,BrokerID= '',UserID=''):
super(ForceUserLogoutField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
class ReqAuthenticateField(Base):
"""客户端认证请求"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('UserProductInfo',ctypes.c_char*11)# 用户端产品信息
,('AuthCode',ctypes.c_char*17)# 认证码
]
def __init__(self,BrokerID= '',UserID='',UserProductInfo='',AuthCode=''):
super(ReqAuthenticateField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.UserProductInfo=self._to_bytes(UserProductInfo)
self.AuthCode=self._to_bytes(AuthCode)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
self.UserProductInfo=self._to_bytes(i_tuple[3])
self.AuthCode=self._to_bytes(i_tuple[4])
class RspAuthenticateField(Base):
"""客户端认证响应"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('UserProductInfo',ctypes.c_char*11)# 用户端产品信息
]
def __init__(self,BrokerID= '',UserID='',UserProductInfo=''):
super(RspAuthenticateField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.UserProductInfo=self._to_bytes(UserProductInfo)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
self.UserProductInfo=self._to_bytes(i_tuple[3])
class AuthenticationInfoField(Base):
"""客户端认证信息"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('UserProductInfo',ctypes.c_char*11)# 用户端产品信息
,('AuthInfo',ctypes.c_char*129)# 认证信息
,('IsResult',ctypes.c_int)# 是否为认证结果
]
def __init__(self,BrokerID= '',UserID='',UserProductInfo='',AuthInfo='',IsResult=0):
super(AuthenticationInfoField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.UserProductInfo=self._to_bytes(UserProductInfo)
self.AuthInfo=self._to_bytes(AuthInfo)
self.IsResult=int(IsResult)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
self.UserProductInfo=self._to_bytes(i_tuple[3])
self.AuthInfo=self._to_bytes(i_tuple[4])
self.IsResult=int(i_tuple[5])
class RspUserLogin2Field(Base):
"""用户登录应答2"""
_fields_ = [
('TradingDay',ctypes.c_char*9)# ///交易日
,('LoginTime',ctypes.c_char*9)# 登录成功时间
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('SystemName',ctypes.c_char*41)# 交易系统名称
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('MaxOrderRef',ctypes.c_char*13)# 最大报单引用
,('SHFETime',ctypes.c_char*9)# 上期所时间
,('DCETime',ctypes.c_char*9)# 大商所时间
,('CZCETime',ctypes.c_char*9)# 郑商所时间
,('FFEXTime',ctypes.c_char*9)# 中金所时间
,('INETime',ctypes.c_char*9)# 能源中心时间
,('RandomString',ctypes.c_char*17)# 随机串
]
def __init__(self,TradingDay= '',LoginTime='',BrokerID='',UserID='',SystemName='',FrontID=0,SessionID=0,MaxOrderRef='',SHFETime='',DCETime='',CZCETime='',FFEXTime='',INETime='',RandomString=''):
super(RspUserLogin2Field,self).__init__()
self.TradingDay=self._to_bytes(TradingDay)
self.LoginTime=self._to_bytes(LoginTime)
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.SystemName=self._to_bytes(SystemName)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.MaxOrderRef=self._to_bytes(MaxOrderRef)
self.SHFETime=self._to_bytes(SHFETime)
self.DCETime=self._to_bytes(DCETime)
self.CZCETime=self._to_bytes(CZCETime)
self.FFEXTime=self._to_bytes(FFEXTime)
self.INETime=self._to_bytes(INETime)
self.RandomString=self._to_bytes(RandomString)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradingDay=self._to_bytes(i_tuple[1])
self.LoginTime=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.UserID=self._to_bytes(i_tuple[4])
self.SystemName=self._to_bytes(i_tuple[5])
self.FrontID=int(i_tuple[6])
self.SessionID=int(i_tuple[7])
self.MaxOrderRef=self._to_bytes(i_tuple[8])
self.SHFETime=self._to_bytes(i_tuple[9])
self.DCETime=self._to_bytes(i_tuple[10])
self.CZCETime=self._to_bytes(i_tuple[11])
self.FFEXTime=self._to_bytes(i_tuple[12])
self.INETime=self._to_bytes(i_tuple[13])
self.RandomString=self._to_bytes(i_tuple[14])
class TransferHeaderField(Base):
"""银期转帐报文头"""
_fields_ = [
('Version',ctypes.c_char*4)# ///版本号,常量,1.0
,('TradeCode',ctypes.c_char*7)# 交易代码,必填
,('TradeDate',ctypes.c_char*9)# 交易日期,必填,格式:yyyymmdd
,('TradeTime',ctypes.c_char*9)# 交易时间,必填,格式:hhmmss
,('TradeSerial',ctypes.c_char*9)# 发起方流水号,N/A
,('FutureID',ctypes.c_char*11)# 期货公司代码,必填
,('BankID',ctypes.c_char*4)# 银行代码,根据查询银行得到,必填
,('BankBrchID',ctypes.c_char*5)# 银行分中心代码,根据查询银行得到,必填
,('OperNo',ctypes.c_char*17)# 操作员,N/A
,('DeviceID',ctypes.c_char*3)# 交易设备类型,N/A
,('RecordNum',ctypes.c_char*7)# 记录数,N/A
,('SessionID',ctypes.c_int)# 会话编号,N/A
,('RequestID',ctypes.c_int)# 请求编号,N/A
]
def __init__(self,Version= '',TradeCode='',TradeDate='',TradeTime='',TradeSerial='',FutureID='',BankID='',BankBrchID='',OperNo='',DeviceID='',RecordNum='',SessionID=0,RequestID=0):
super(TransferHeaderField,self).__init__()
self.Version=self._to_bytes(Version)
self.TradeCode=self._to_bytes(TradeCode)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.TradeSerial=self._to_bytes(TradeSerial)
self.FutureID=self._to_bytes(FutureID)
self.BankID=self._to_bytes(BankID)
self.BankBrchID=self._to_bytes(BankBrchID)
self.OperNo=self._to_bytes(OperNo)
self.DeviceID=self._to_bytes(DeviceID)
self.RecordNum=self._to_bytes(RecordNum)
self.SessionID=int(SessionID)
self.RequestID=int(RequestID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.Version=self._to_bytes(i_tuple[1])
self.TradeCode=self._to_bytes(i_tuple[2])
self.TradeDate=self._to_bytes(i_tuple[3])
self.TradeTime=self._to_bytes(i_tuple[4])
self.TradeSerial=self._to_bytes(i_tuple[5])
self.FutureID=self._to_bytes(i_tuple[6])
self.BankID=self._to_bytes(i_tuple[7])
self.BankBrchID=self._to_bytes(i_tuple[8])
self.OperNo=self._to_bytes(i_tuple[9])
self.DeviceID=self._to_bytes(i_tuple[10])
self.RecordNum=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.RequestID=int(i_tuple[13])
class TransferBankToFutureReqField(Base):
"""银行资金转期货请求,TradeCode=202001"""
_fields_ = [
('FutureAccount',ctypes.c_char*13)# ///期货资金账户
,('FuturePwdFlag',ctypes.c_char)# 密码标志
,('FutureAccPwd',ctypes.c_char*17)# 密码
,('TradeAmt',ctypes.c_double)# 转账金额
,('CustFee',ctypes.c_double)# 客户手续费
,('CurrencyCode',ctypes.c_char*4)# 币种:RMB-人民币 USD-美圆 HKD-港元
]
def __init__(self,FutureAccount= '',FuturePwdFlag='',FutureAccPwd='',TradeAmt=0.0,CustFee=0.0,CurrencyCode=''):
super(TransferBankToFutureReqField,self).__init__()
self.FutureAccount=self._to_bytes(FutureAccount)
self.FuturePwdFlag=self._to_bytes(FuturePwdFlag)
self.FutureAccPwd=self._to_bytes(FutureAccPwd)
self.TradeAmt=float(TradeAmt)
self.CustFee=float(CustFee)
self.CurrencyCode=self._to_bytes(CurrencyCode)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.FutureAccount=self._to_bytes(i_tuple[1])
self.FuturePwdFlag=self._to_bytes(i_tuple[2])
self.FutureAccPwd=self._to_bytes(i_tuple[3])
self.TradeAmt=float(i_tuple[4])
self.CustFee=float(i_tuple[5])
self.CurrencyCode=self._to_bytes(i_tuple[6])
class TransferBankToFutureRspField(Base):
"""银行资金转期货请求响应"""
_fields_ = [
('RetCode',ctypes.c_char*5)# ///响应代码
,('RetInfo',ctypes.c_char*129)# 响应信息
,('FutureAccount',ctypes.c_char*13)# 资金账户
,('TradeAmt',ctypes.c_double)# 转帐金额
,('CustFee',ctypes.c_double)# 应收客户手续费
,('CurrencyCode',ctypes.c_char*4)# 币种
]
def __init__(self,RetCode= '',RetInfo='',FutureAccount='',TradeAmt=0.0,CustFee=0.0,CurrencyCode=''):
super(TransferBankToFutureRspField,self).__init__()
self.RetCode=self._to_bytes(RetCode)
self.RetInfo=self._to_bytes(RetInfo)
self.FutureAccount=self._to_bytes(FutureAccount)
self.TradeAmt=float(TradeAmt)
self.CustFee=float(CustFee)
self.CurrencyCode=self._to_bytes(CurrencyCode)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.RetCode=self._to_bytes(i_tuple[1])
self.RetInfo=self._to_bytes(i_tuple[2])
self.FutureAccount=self._to_bytes(i_tuple[3])
self.TradeAmt=float(i_tuple[4])
self.CustFee=float(i_tuple[5])
self.CurrencyCode=self._to_bytes(i_tuple[6])
class TransferFutureToBankReqField(Base):
"""期货资金转银行请求,TradeCode=202002"""
_fields_ = [
('FutureAccount',ctypes.c_char*13)# ///期货资金账户
,('FuturePwdFlag',ctypes.c_char)# 密码标志
,('FutureAccPwd',ctypes.c_char*17)# 密码
,('TradeAmt',ctypes.c_double)# 转账金额
,('CustFee',ctypes.c_double)# 客户手续费
,('CurrencyCode',ctypes.c_char*4)# 币种:RMB-人民币 USD-美圆 HKD-港元
]
def __init__(self,FutureAccount= '',FuturePwdFlag='',FutureAccPwd='',TradeAmt=0.0,CustFee=0.0,CurrencyCode=''):
super(TransferFutureToBankReqField,self).__init__()
self.FutureAccount=self._to_bytes(FutureAccount)
self.FuturePwdFlag=self._to_bytes(FuturePwdFlag)
self.FutureAccPwd=self._to_bytes(FutureAccPwd)
self.TradeAmt=float(TradeAmt)
self.CustFee=float(CustFee)
self.CurrencyCode=self._to_bytes(CurrencyCode)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.FutureAccount=self._to_bytes(i_tuple[1])
self.FuturePwdFlag=self._to_bytes(i_tuple[2])
self.FutureAccPwd=self._to_bytes(i_tuple[3])
self.TradeAmt=float(i_tuple[4])
self.CustFee=float(i_tuple[5])
self.CurrencyCode=self._to_bytes(i_tuple[6])
class TransferFutureToBankRspField(Base):
"""期货资金转银行请求响应"""
_fields_ = [
('RetCode',ctypes.c_char*5)# ///响应代码
,('RetInfo',ctypes.c_char*129)# 响应信息
,('FutureAccount',ctypes.c_char*13)# 资金账户
,('TradeAmt',ctypes.c_double)# 转帐金额
,('CustFee',ctypes.c_double)# 应收客户手续费
,('CurrencyCode',ctypes.c_char*4)# 币种
]
def __init__(self,RetCode= '',RetInfo='',FutureAccount='',TradeAmt=0.0,CustFee=0.0,CurrencyCode=''):
super(TransferFutureToBankRspField,self).__init__()
self.RetCode=self._to_bytes(RetCode)
self.RetInfo=self._to_bytes(RetInfo)
self.FutureAccount=self._to_bytes(FutureAccount)
self.TradeAmt=float(TradeAmt)
self.CustFee=float(CustFee)
self.CurrencyCode=self._to_bytes(CurrencyCode)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.RetCode=self._to_bytes(i_tuple[1])
self.RetInfo=self._to_bytes(i_tuple[2])
self.FutureAccount=self._to_bytes(i_tuple[3])
self.TradeAmt=float(i_tuple[4])
self.CustFee=float(i_tuple[5])
self.CurrencyCode=self._to_bytes(i_tuple[6])
class TransferQryBankReqField(Base):
"""查询银行资金请求,TradeCode=204002"""
_fields_ = [
('FutureAccount',ctypes.c_char*13)# ///期货资金账户
,('FuturePwdFlag',ctypes.c_char)# 密码标志
,('FutureAccPwd',ctypes.c_char*17)# 密码
,('CurrencyCode',ctypes.c_char*4)# 币种:RMB-人民币 USD-美圆 HKD-港元
]
def __init__(self,FutureAccount= '',FuturePwdFlag='',FutureAccPwd='',CurrencyCode=''):
super(TransferQryBankReqField,self).__init__()
self.FutureAccount=self._to_bytes(FutureAccount)
self.FuturePwdFlag=self._to_bytes(FuturePwdFlag)
self.FutureAccPwd=self._to_bytes(FutureAccPwd)
self.CurrencyCode=self._to_bytes(CurrencyCode)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.FutureAccount=self._to_bytes(i_tuple[1])
self.FuturePwdFlag=self._to_bytes(i_tuple[2])
self.FutureAccPwd=self._to_bytes(i_tuple[3])
self.CurrencyCode=self._to_bytes(i_tuple[4])
class TransferQryBankRspField(Base):
"""查询银行资金请求响应"""
_fields_ = [
('RetCode',ctypes.c_char*5)# ///响应代码
,('RetInfo',ctypes.c_char*129)# 响应信息
,('FutureAccount',ctypes.c_char*13)# 资金账户
,('TradeAmt',ctypes.c_double)# 银行余额
,('UseAmt',ctypes.c_double)# 银行可用余额
,('FetchAmt',ctypes.c_double)# 银行可取余额
,('CurrencyCode',ctypes.c_char*4)# 币种
]
def __init__(self,RetCode= '',RetInfo='',FutureAccount='',TradeAmt=0.0,UseAmt=0.0,FetchAmt=0.0,CurrencyCode=''):
super(TransferQryBankRspField,self).__init__()
self.RetCode=self._to_bytes(RetCode)
self.RetInfo=self._to_bytes(RetInfo)
self.FutureAccount=self._to_bytes(FutureAccount)
self.TradeAmt=float(TradeAmt)
self.UseAmt=float(UseAmt)
self.FetchAmt=float(FetchAmt)
self.CurrencyCode=self._to_bytes(CurrencyCode)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.RetCode=self._to_bytes(i_tuple[1])
self.RetInfo=self._to_bytes(i_tuple[2])
self.FutureAccount=self._to_bytes(i_tuple[3])
self.TradeAmt=float(i_tuple[4])
self.UseAmt=float(i_tuple[5])
self.FetchAmt=float(i_tuple[6])
self.CurrencyCode=self._to_bytes(i_tuple[7])
class TransferQryDetailReqField(Base):
"""查询银行交易明细请求,TradeCode=204999"""
_fields_ = [
('FutureAccount',ctypes.c_char*13)# ///期货资金账户
]
def __init__(self,FutureAccount= ''):
super(TransferQryDetailReqField,self).__init__()
self.FutureAccount=self._to_bytes(FutureAccount)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.FutureAccount=self._to_bytes(i_tuple[1])
class TransferQryDetailRspField(Base):
"""查询银行交易明细请求响应"""
_fields_ = [
('TradeDate',ctypes.c_char*9)# ///交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('TradeCode',ctypes.c_char*7)# 交易代码
,('FutureSerial',ctypes.c_int)# 期货流水号
,('FutureID',ctypes.c_char*11)# 期货公司代码
,('FutureAccount',ctypes.c_char*22)# 资金帐号
,('BankSerial',ctypes.c_int)# 银行流水号
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBrchID',ctypes.c_char*5)# 银行分中心代码
,('BankAccount',ctypes.c_char*41)# 银行账号
,('CertCode',ctypes.c_char*21)# 证件号码
,('CurrencyCode',ctypes.c_char*4)# 货币代码
,('TxAmount',ctypes.c_double)# 发生金额
,('Flag',ctypes.c_char)# 有效标志
]
def __init__(self,TradeDate= '',TradeTime='',TradeCode='',FutureSerial=0,FutureID='',FutureAccount='',BankSerial=0,BankID='',BankBrchID='',BankAccount='',CertCode='',CurrencyCode='',TxAmount=0.0,Flag=''):
super(TransferQryDetailRspField,self).__init__()
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.TradeCode=self._to_bytes(TradeCode)
self.FutureSerial=int(FutureSerial)
self.FutureID=self._to_bytes(FutureID)
self.FutureAccount=self._to_bytes(FutureAccount)
self.BankSerial=int(BankSerial)
self.BankID=self._to_bytes(BankID)
self.BankBrchID=self._to_bytes(BankBrchID)
self.BankAccount=self._to_bytes(BankAccount)
self.CertCode=self._to_bytes(CertCode)
self.CurrencyCode=self._to_bytes(CurrencyCode)
self.TxAmount=float(TxAmount)
self.Flag=self._to_bytes(Flag)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeDate=self._to_bytes(i_tuple[1])
self.TradeTime=self._to_bytes(i_tuple[2])
self.TradeCode=self._to_bytes(i_tuple[3])
self.FutureSerial=int(i_tuple[4])
self.FutureID=self._to_bytes(i_tuple[5])
self.FutureAccount=self._to_bytes(i_tuple[6])
self.BankSerial=int(i_tuple[7])
self.BankID=self._to_bytes(i_tuple[8])
self.BankBrchID=self._to_bytes(i_tuple[9])
self.BankAccount=self._to_bytes(i_tuple[10])
self.CertCode=self._to_bytes(i_tuple[11])
self.CurrencyCode=self._to_bytes(i_tuple[12])
self.TxAmount=float(i_tuple[13])
self.Flag=self._to_bytes(i_tuple[14])
class RspInfoField(Base):
"""响应信息"""
_fields_ = [
('ErrorID',ctypes.c_int)# ///错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
]
def __init__(self,ErrorID= 0,ErrorMsg=''):
super(RspInfoField,self).__init__()
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ErrorID=int(i_tuple[1])
self.ErrorMsg=self._to_bytes(i_tuple[2])
class ExchangeField(Base):
"""交易所"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('ExchangeName',ctypes.c_char*61)# 交易所名称
,('ExchangeProperty',ctypes.c_char)# 交易所属性
]
def __init__(self,ExchangeID= '',ExchangeName='',ExchangeProperty=''):
super(ExchangeField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.ExchangeName=self._to_bytes(ExchangeName)
self.ExchangeProperty=self._to_bytes(ExchangeProperty)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.ExchangeName=self._to_bytes(i_tuple[2])
self.ExchangeProperty=self._to_bytes(i_tuple[3])
class ProductField(Base):
"""产品"""
_fields_ = [
('ProductID',ctypes.c_char*31)# ///产品代码
,('ProductName',ctypes.c_char*21)# 产品名称
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ProductClass',ctypes.c_char)# 产品类型
,('VolumeMultiple',ctypes.c_int)# 合约数量乘数
,('PriceTick',ctypes.c_double)# 最小变动价位
,('MaxMarketOrderVolume',ctypes.c_int)# 市价单最大下单量
,('MinMarketOrderVolume',ctypes.c_int)# 市价单最小下单量
,('MaxLimitOrderVolume',ctypes.c_int)# 限价单最大下单量
,('MinLimitOrderVolume',ctypes.c_int)# 限价单最小下单量
,('PositionType',ctypes.c_char)# 持仓类型
,('PositionDateType',ctypes.c_char)# 持仓日期类型
,('CloseDealType',ctypes.c_char)# 平仓处理类型
,('TradeCurrencyID',ctypes.c_char*4)# 交易币种类型
,('MortgageFundUseRange',ctypes.c_char)# 质押资金可用范围
,('ExchangeProductID',ctypes.c_char*31)# 交易所产品代码
,('UnderlyingMultiple',ctypes.c_double)# 合约基础商品乘数
]
def __init__(self,ProductID= '',ProductName='',ExchangeID='',ProductClass='',VolumeMultiple=0,PriceTick=0.0,MaxMarketOrderVolume=0,MinMarketOrderVolume=0,MaxLimitOrderVolume=0,MinLimitOrderVolume=0,PositionType='',PositionDateType='',CloseDealType='',TradeCurrencyID='',MortgageFundUseRange='',ExchangeProductID='',UnderlyingMultiple=0.0):
super(ProductField,self).__init__()
self.ProductID=self._to_bytes(ProductID)
self.ProductName=self._to_bytes(ProductName)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ProductClass=self._to_bytes(ProductClass)
self.VolumeMultiple=int(VolumeMultiple)
self.PriceTick=float(PriceTick)
self.MaxMarketOrderVolume=int(MaxMarketOrderVolume)
self.MinMarketOrderVolume=int(MinMarketOrderVolume)
self.MaxLimitOrderVolume=int(MaxLimitOrderVolume)
self.MinLimitOrderVolume=int(MinLimitOrderVolume)
self.PositionType=self._to_bytes(PositionType)
self.PositionDateType=self._to_bytes(PositionDateType)
self.CloseDealType=self._to_bytes(CloseDealType)
self.TradeCurrencyID=self._to_bytes(TradeCurrencyID)
self.MortgageFundUseRange=self._to_bytes(MortgageFundUseRange)
self.ExchangeProductID=self._to_bytes(ExchangeProductID)
self.UnderlyingMultiple=float(UnderlyingMultiple)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ProductID=self._to_bytes(i_tuple[1])
self.ProductName=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
self.ProductClass=self._to_bytes(i_tuple[4])
self.VolumeMultiple=int(i_tuple[5])
self.PriceTick=float(i_tuple[6])
self.MaxMarketOrderVolume=int(i_tuple[7])
self.MinMarketOrderVolume=int(i_tuple[8])
self.MaxLimitOrderVolume=int(i_tuple[9])
self.MinLimitOrderVolume=int(i_tuple[10])
self.PositionType=self._to_bytes(i_tuple[11])
self.PositionDateType=self._to_bytes(i_tuple[12])
self.CloseDealType=self._to_bytes(i_tuple[13])
self.TradeCurrencyID=self._to_bytes(i_tuple[14])
self.MortgageFundUseRange=self._to_bytes(i_tuple[15])
self.ExchangeProductID=self._to_bytes(i_tuple[16])
self.UnderlyingMultiple=float(i_tuple[17])
class InstrumentField(Base):
"""合约"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InstrumentName',ctypes.c_char*21)# 合约名称
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('ProductID',ctypes.c_char*31)# 产品代码
,('ProductClass',ctypes.c_char)# 产品类型
,('DeliveryYear',ctypes.c_int)# 交割年份
,('DeliveryMonth',ctypes.c_int)# 交割月
,('MaxMarketOrderVolume',ctypes.c_int)# 市价单最大下单量
,('MinMarketOrderVolume',ctypes.c_int)# 市价单最小下单量
,('MaxLimitOrderVolume',ctypes.c_int)# 限价单最大下单量
,('MinLimitOrderVolume',ctypes.c_int)# 限价单最小下单量
,('VolumeMultiple',ctypes.c_int)# 合约数量乘数
,('PriceTick',ctypes.c_double)# 最小变动价位
,('CreateDate',ctypes.c_char*9)# 创建日
,('OpenDate',ctypes.c_char*9)# 上市日
,('ExpireDate',ctypes.c_char*9)# 到期日
,('StartDelivDate',ctypes.c_char*9)# 开始交割日
,('EndDelivDate',ctypes.c_char*9)# 结束交割日
,('InstLifePhase',ctypes.c_char)# 合约生命周期状态
,('IsTrading',ctypes.c_int)# 当前是否交易
,('PositionType',ctypes.c_char)# 持仓类型
,('PositionDateType',ctypes.c_char)# 持仓日期类型
,('LongMarginRatio',ctypes.c_double)# 多头保证金率
,('ShortMarginRatio',ctypes.c_double)# 空头保证金率
,('MaxMarginSideAlgorithm',ctypes.c_char)# 是否使用大额单边保证金算法
,('UnderlyingInstrID',ctypes.c_char*31)# 基础商品代码
,('StrikePrice',ctypes.c_double)# 执行价
,('OptionsType',ctypes.c_char)# 期权类型
,('UnderlyingMultiple',ctypes.c_double)# 合约基础商品乘数
,('CombinationType',ctypes.c_char)# 组合类型
]
def __init__(self,InstrumentID= '',ExchangeID='',InstrumentName='',ExchangeInstID='',ProductID='',ProductClass='',DeliveryYear=0,DeliveryMonth=0,MaxMarketOrderVolume=0,MinMarketOrderVolume=0,MaxLimitOrderVolume=0,MinLimitOrderVolume=0,VolumeMultiple=0,PriceTick=0.0,CreateDate='',OpenDate='',ExpireDate='',StartDelivDate='',EndDelivDate='',InstLifePhase='',IsTrading=0,PositionType='',PositionDateType='',LongMarginRatio=0.0,ShortMarginRatio=0.0,MaxMarginSideAlgorithm='',UnderlyingInstrID='',StrikePrice=0.0,OptionsType='',UnderlyingMultiple=0.0,CombinationType=''):
super(InstrumentField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InstrumentName=self._to_bytes(InstrumentName)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.ProductID=self._to_bytes(ProductID)
self.ProductClass=self._to_bytes(ProductClass)
self.DeliveryYear=int(DeliveryYear)
self.DeliveryMonth=int(DeliveryMonth)
self.MaxMarketOrderVolume=int(MaxMarketOrderVolume)
self.MinMarketOrderVolume=int(MinMarketOrderVolume)
self.MaxLimitOrderVolume=int(MaxLimitOrderVolume)
self.MinLimitOrderVolume=int(MinLimitOrderVolume)
self.VolumeMultiple=int(VolumeMultiple)
self.PriceTick=float(PriceTick)
self.CreateDate=self._to_bytes(CreateDate)
self.OpenDate=self._to_bytes(OpenDate)
self.ExpireDate=self._to_bytes(ExpireDate)
self.StartDelivDate=self._to_bytes(StartDelivDate)
self.EndDelivDate=self._to_bytes(EndDelivDate)
self.InstLifePhase=self._to_bytes(InstLifePhase)
self.IsTrading=int(IsTrading)
self.PositionType=self._to_bytes(PositionType)
self.PositionDateType=self._to_bytes(PositionDateType)
self.LongMarginRatio=float(LongMarginRatio)
self.ShortMarginRatio=float(ShortMarginRatio)
self.MaxMarginSideAlgorithm=self._to_bytes(MaxMarginSideAlgorithm)
self.UnderlyingInstrID=self._to_bytes(UnderlyingInstrID)
self.StrikePrice=float(StrikePrice)
self.OptionsType=self._to_bytes(OptionsType)
self.UnderlyingMultiple=float(UnderlyingMultiple)
self.CombinationType=self._to_bytes(CombinationType)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.ExchangeID=self._to_bytes(i_tuple[2])
self.InstrumentName=self._to_bytes(i_tuple[3])
self.ExchangeInstID=self._to_bytes(i_tuple[4])
self.ProductID=self._to_bytes(i_tuple[5])
self.ProductClass=self._to_bytes(i_tuple[6])
self.DeliveryYear=int(i_tuple[7])
self.DeliveryMonth=int(i_tuple[8])
self.MaxMarketOrderVolume=int(i_tuple[9])
self.MinMarketOrderVolume=int(i_tuple[10])
self.MaxLimitOrderVolume=int(i_tuple[11])
self.MinLimitOrderVolume=int(i_tuple[12])
self.VolumeMultiple=int(i_tuple[13])
self.PriceTick=float(i_tuple[14])
self.CreateDate=self._to_bytes(i_tuple[15])
self.OpenDate=self._to_bytes(i_tuple[16])
self.ExpireDate=self._to_bytes(i_tuple[17])
self.StartDelivDate=self._to_bytes(i_tuple[18])
self.EndDelivDate=self._to_bytes(i_tuple[19])
self.InstLifePhase=self._to_bytes(i_tuple[20])
self.IsTrading=int(i_tuple[21])
self.PositionType=self._to_bytes(i_tuple[22])
self.PositionDateType=self._to_bytes(i_tuple[23])
self.LongMarginRatio=float(i_tuple[24])
self.ShortMarginRatio=float(i_tuple[25])
self.MaxMarginSideAlgorithm=self._to_bytes(i_tuple[26])
self.UnderlyingInstrID=self._to_bytes(i_tuple[27])
self.StrikePrice=float(i_tuple[28])
self.OptionsType=self._to_bytes(i_tuple[29])
self.UnderlyingMultiple=float(i_tuple[30])
self.CombinationType=self._to_bytes(i_tuple[31])
class BrokerField(Base):
"""经纪公司"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('BrokerAbbr',ctypes.c_char*9)# 经纪公司简称
,('BrokerName',ctypes.c_char*81)# 经纪公司名称
,('IsActive',ctypes.c_int)# 是否活跃
]
def __init__(self,BrokerID= '',BrokerAbbr='',BrokerName='',IsActive=0):
super(BrokerField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerAbbr=self._to_bytes(BrokerAbbr)
self.BrokerName=self._to_bytes(BrokerName)
self.IsActive=int(IsActive)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.BrokerAbbr=self._to_bytes(i_tuple[2])
self.BrokerName=self._to_bytes(i_tuple[3])
self.IsActive=int(i_tuple[4])
class TraderField(Base):
"""交易所交易员"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('Password',ctypes.c_char*41)# 密码
,('InstallCount',ctypes.c_int)# 安装数量
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
]
def __init__(self,ExchangeID= '',TraderID='',ParticipantID='',Password='',InstallCount=0,BrokerID=''):
super(TraderField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.TraderID=self._to_bytes(TraderID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.Password=self._to_bytes(Password)
self.InstallCount=int(InstallCount)
self.BrokerID=self._to_bytes(BrokerID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.TraderID=self._to_bytes(i_tuple[2])
self.ParticipantID=self._to_bytes(i_tuple[3])
self.Password=self._to_bytes(i_tuple[4])
self.InstallCount=int(i_tuple[5])
self.BrokerID=self._to_bytes(i_tuple[6])
class InvestorField(Base):
"""投资者"""
_fields_ = [
('InvestorID',ctypes.c_char*13)# ///投资者代码
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorGroupID',ctypes.c_char*13)# 投资者分组代码
,('InvestorName',ctypes.c_char*81)# 投资者名称
,('IdentifiedCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('IsActive',ctypes.c_int)# 是否活跃
,('Telephone',ctypes.c_char*41)# 联系电话
,('Address',ctypes.c_char*101)# 通讯地址
,('OpenDate',ctypes.c_char*9)# 开户日期
,('Mobile',ctypes.c_char*41)# 手机
,('CommModelID',ctypes.c_char*13)# 手续费率模板代码
,('MarginModelID',ctypes.c_char*13)# 保证金率模板代码
]
def __init__(self,InvestorID= '',BrokerID='',InvestorGroupID='',InvestorName='',IdentifiedCardType='',IdentifiedCardNo='',IsActive=0,Telephone='',Address='',OpenDate='',Mobile='',CommModelID='',MarginModelID=''):
super(InvestorField,self).__init__()
self.InvestorID=self._to_bytes(InvestorID)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorGroupID=self._to_bytes(InvestorGroupID)
self.InvestorName=self._to_bytes(InvestorName)
self.IdentifiedCardType=self._to_bytes(IdentifiedCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.IsActive=int(IsActive)
self.Telephone=self._to_bytes(Telephone)
self.Address=self._to_bytes(Address)
self.OpenDate=self._to_bytes(OpenDate)
self.Mobile=self._to_bytes(Mobile)
self.CommModelID=self._to_bytes(CommModelID)
self.MarginModelID=self._to_bytes(MarginModelID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InvestorID=self._to_bytes(i_tuple[1])
self.BrokerID=self._to_bytes(i_tuple[2])
self.InvestorGroupID=self._to_bytes(i_tuple[3])
self.InvestorName=self._to_bytes(i_tuple[4])
self.IdentifiedCardType=self._to_bytes(i_tuple[5])
self.IdentifiedCardNo=self._to_bytes(i_tuple[6])
self.IsActive=int(i_tuple[7])
self.Telephone=self._to_bytes(i_tuple[8])
self.Address=self._to_bytes(i_tuple[9])
self.OpenDate=self._to_bytes(i_tuple[10])
self.Mobile=self._to_bytes(i_tuple[11])
self.CommModelID=self._to_bytes(i_tuple[12])
self.MarginModelID=self._to_bytes(i_tuple[13])
class TradingCodeField(Base):
"""交易编码"""
_fields_ = [
('InvestorID',ctypes.c_char*13)# ///投资者代码
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('IsActive',ctypes.c_int)# 是否活跃
,('ClientIDType',ctypes.c_char)# 交易编码类型
,('BranchID',ctypes.c_char*9)# 营业部编号
,('BizType',ctypes.c_char)# 业务类型
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,InvestorID= '',BrokerID='',ExchangeID='',ClientID='',IsActive=0,ClientIDType='',BranchID='',BizType='',InvestUnitID=''):
super(TradingCodeField,self).__init__()
self.InvestorID=self._to_bytes(InvestorID)
self.BrokerID=self._to_bytes(BrokerID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ClientID=self._to_bytes(ClientID)
self.IsActive=int(IsActive)
self.ClientIDType=self._to_bytes(ClientIDType)
self.BranchID=self._to_bytes(BranchID)
self.BizType=self._to_bytes(BizType)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InvestorID=self._to_bytes(i_tuple[1])
self.BrokerID=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
self.ClientID=self._to_bytes(i_tuple[4])
self.IsActive=int(i_tuple[5])
self.ClientIDType=self._to_bytes(i_tuple[6])
self.BranchID=self._to_bytes(i_tuple[7])
self.BizType=self._to_bytes(i_tuple[8])
self.InvestUnitID=self._to_bytes(i_tuple[9])
class PartBrokerField(Base):
"""会员编码和经纪公司编码对照表"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('IsActive',ctypes.c_int)# 是否活跃
]
def __init__(self,BrokerID= '',ExchangeID='',ParticipantID='',IsActive=0):
super(PartBrokerField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.IsActive=int(IsActive)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.ExchangeID=self._to_bytes(i_tuple[2])
self.ParticipantID=self._to_bytes(i_tuple[3])
self.IsActive=int(i_tuple[4])
class SuperUserField(Base):
"""管理用户"""
_fields_ = [
('UserID',ctypes.c_char*16)# ///用户代码
,('UserName',ctypes.c_char*81)# 用户名称
,('Password',ctypes.c_char*41)# 密码
,('IsActive',ctypes.c_int)# 是否活跃
]
def __init__(self,UserID= '',UserName='',Password='',IsActive=0):
super(SuperUserField,self).__init__()
self.UserID=self._to_bytes(UserID)
self.UserName=self._to_bytes(UserName)
self.Password=self._to_bytes(Password)
self.IsActive=int(IsActive)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.UserID=self._to_bytes(i_tuple[1])
self.UserName=self._to_bytes(i_tuple[2])
self.Password=self._to_bytes(i_tuple[3])
self.IsActive=int(i_tuple[4])
class SuperUserFunctionField(Base):
"""管理用户功能权限"""
_fields_ = [
('UserID',ctypes.c_char*16)# ///用户代码
,('FunctionCode',ctypes.c_char)# 功能代码
]
def __init__(self,UserID= '',FunctionCode=''):
super(SuperUserFunctionField,self).__init__()
self.UserID=self._to_bytes(UserID)
self.FunctionCode=self._to_bytes(FunctionCode)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.UserID=self._to_bytes(i_tuple[1])
self.FunctionCode=self._to_bytes(i_tuple[2])
class InvestorGroupField(Base):
"""投资者组"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorGroupID',ctypes.c_char*13)# 投资者分组代码
,('InvestorGroupName',ctypes.c_char*41)# 投资者分组名称
]
def __init__(self,BrokerID= '',InvestorGroupID='',InvestorGroupName=''):
super(InvestorGroupField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorGroupID=self._to_bytes(InvestorGroupID)
self.InvestorGroupName=self._to_bytes(InvestorGroupName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorGroupID=self._to_bytes(i_tuple[2])
self.InvestorGroupName=self._to_bytes(i_tuple[3])
class TradingAccountField(Base):
"""资金账户"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('PreMortgage',ctypes.c_double)# 上次质押金额
,('PreCredit',ctypes.c_double)# 上次信用额度
,('PreDeposit',ctypes.c_double)# 上次存款额
,('PreBalance',ctypes.c_double)# 上次结算准备金
,('PreMargin',ctypes.c_double)# 上次占用的保证金
,('InterestBase',ctypes.c_double)# 利息基数
,('Interest',ctypes.c_double)# 利息收入
,('Deposit',ctypes.c_double)# 入金金额
,('Withdraw',ctypes.c_double)# 出金金额
,('FrozenMargin',ctypes.c_double)# 冻结的保证金
,('FrozenCash',ctypes.c_double)# 冻结的资金
,('FrozenCommission',ctypes.c_double)# 冻结的手续费
,('CurrMargin',ctypes.c_double)# 当前保证金总额
,('CashIn',ctypes.c_double)# 资金差额
,('Commission',ctypes.c_double)# 手续费
,('CloseProfit',ctypes.c_double)# 平仓盈亏
,('PositionProfit',ctypes.c_double)# 持仓盈亏
,('Balance',ctypes.c_double)# 期货结算准备金
,('Available',ctypes.c_double)# 可用资金
,('WithdrawQuota',ctypes.c_double)# 可取资金
,('Reserve',ctypes.c_double)# 基本准备金
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('Credit',ctypes.c_double)# 信用额度
,('Mortgage',ctypes.c_double)# 质押金额
,('ExchangeMargin',ctypes.c_double)# 交易所保证金
,('DeliveryMargin',ctypes.c_double)# 投资者交割保证金
,('ExchangeDeliveryMargin',ctypes.c_double)# 交易所交割保证金
,('ReserveBalance',ctypes.c_double)# 保底期货结算准备金
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('PreFundMortgageIn',ctypes.c_double)# 上次货币质入金额
,('PreFundMortgageOut',ctypes.c_double)# 上次货币质出金额
,('FundMortgageIn',ctypes.c_double)# 货币质入金额
,('FundMortgageOut',ctypes.c_double)# 货币质出金额
,('FundMortgageAvailable',ctypes.c_double)# 货币质押余额
,('MortgageableFund',ctypes.c_double)# 可质押货币金额
,('SpecProductMargin',ctypes.c_double)# 特殊产品占用保证金
,('SpecProductFrozenMargin',ctypes.c_double)# 特殊产品冻结保证金
,('SpecProductCommission',ctypes.c_double)# 特殊产品手续费
,('SpecProductFrozenCommission',ctypes.c_double)# 特殊产品冻结手续费
,('SpecProductPositionProfit',ctypes.c_double)# 特殊产品持仓盈亏
,('SpecProductCloseProfit',ctypes.c_double)# 特殊产品平仓盈亏
,('SpecProductPositionProfitByAlg',ctypes.c_double)# 根据持仓盈亏算法计算的特殊产品持仓盈亏
,('SpecProductExchangeMargin',ctypes.c_double)# 特殊产品交易所保证金
,('BizType',ctypes.c_char)# 业务类型
,('FrozenSwap',ctypes.c_double)# 延时换汇冻结金额
,('RemainSwap',ctypes.c_double)# 剩余换汇额度
]
def __init__(self,BrokerID= '',AccountID='',PreMortgage=0.0,PreCredit=0.0,PreDeposit=0.0,PreBalance=0.0,PreMargin=0.0,InterestBase=0.0,Interest=0.0,Deposit=0.0,Withdraw=0.0,FrozenMargin=0.0,FrozenCash=0.0,FrozenCommission=0.0,CurrMargin=0.0,CashIn=0.0,Commission=0.0,CloseProfit=0.0,PositionProfit=0.0,Balance=0.0,Available=0.0,WithdrawQuota=0.0,Reserve=0.0,TradingDay='',SettlementID=0,Credit=0.0,Mortgage=0.0,ExchangeMargin=0.0,DeliveryMargin=0.0,ExchangeDeliveryMargin=0.0,ReserveBalance=0.0,CurrencyID='',PreFundMortgageIn=0.0,PreFundMortgageOut=0.0,FundMortgageIn=0.0,FundMortgageOut=0.0,FundMortgageAvailable=0.0,MortgageableFund=0.0,SpecProductMargin=0.0,SpecProductFrozenMargin=0.0,SpecProductCommission=0.0,SpecProductFrozenCommission=0.0,SpecProductPositionProfit=0.0,SpecProductCloseProfit=0.0,SpecProductPositionProfitByAlg=0.0,SpecProductExchangeMargin=0.0,BizType='',FrozenSwap=0.0,RemainSwap=0.0):
super(TradingAccountField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.AccountID=self._to_bytes(AccountID)
self.PreMortgage=float(PreMortgage)
self.PreCredit=float(PreCredit)
self.PreDeposit=float(PreDeposit)
self.PreBalance=float(PreBalance)
self.PreMargin=float(PreMargin)
self.InterestBase=float(InterestBase)
self.Interest=float(Interest)
self.Deposit=float(Deposit)
self.Withdraw=float(Withdraw)
self.FrozenMargin=float(FrozenMargin)
self.FrozenCash=float(FrozenCash)
self.FrozenCommission=float(FrozenCommission)
self.CurrMargin=float(CurrMargin)
self.CashIn=float(CashIn)
self.Commission=float(Commission)
self.CloseProfit=float(CloseProfit)
self.PositionProfit=float(PositionProfit)
self.Balance=float(Balance)
self.Available=float(Available)
self.WithdrawQuota=float(WithdrawQuota)
self.Reserve=float(Reserve)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.Credit=float(Credit)
self.Mortgage=float(Mortgage)
self.ExchangeMargin=float(ExchangeMargin)
self.DeliveryMargin=float(DeliveryMargin)
self.ExchangeDeliveryMargin=float(ExchangeDeliveryMargin)
self.ReserveBalance=float(ReserveBalance)
self.CurrencyID=self._to_bytes(CurrencyID)
self.PreFundMortgageIn=float(PreFundMortgageIn)
self.PreFundMortgageOut=float(PreFundMortgageOut)
self.FundMortgageIn=float(FundMortgageIn)
self.FundMortgageOut=float(FundMortgageOut)
self.FundMortgageAvailable=float(FundMortgageAvailable)
self.MortgageableFund=float(MortgageableFund)
self.SpecProductMargin=float(SpecProductMargin)
self.SpecProductFrozenMargin=float(SpecProductFrozenMargin)
self.SpecProductCommission=float(SpecProductCommission)
self.SpecProductFrozenCommission=float(SpecProductFrozenCommission)
self.SpecProductPositionProfit=float(SpecProductPositionProfit)
self.SpecProductCloseProfit=float(SpecProductCloseProfit)
self.SpecProductPositionProfitByAlg=float(SpecProductPositionProfitByAlg)
self.SpecProductExchangeMargin=float(SpecProductExchangeMargin)
self.BizType=self._to_bytes(BizType)
self.FrozenSwap=float(FrozenSwap)
self.RemainSwap=float(RemainSwap)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.AccountID=self._to_bytes(i_tuple[2])
self.PreMortgage=float(i_tuple[3])
self.PreCredit=float(i_tuple[4])
self.PreDeposit=float(i_tuple[5])
self.PreBalance=float(i_tuple[6])
self.PreMargin=float(i_tuple[7])
self.InterestBase=float(i_tuple[8])
self.Interest=float(i_tuple[9])
self.Deposit=float(i_tuple[10])
self.Withdraw=float(i_tuple[11])
self.FrozenMargin=float(i_tuple[12])
self.FrozenCash=float(i_tuple[13])
self.FrozenCommission=float(i_tuple[14])
self.CurrMargin=float(i_tuple[15])
self.CashIn=float(i_tuple[16])
self.Commission=float(i_tuple[17])
self.CloseProfit=float(i_tuple[18])
self.PositionProfit=float(i_tuple[19])
self.Balance=float(i_tuple[20])
self.Available=float(i_tuple[21])
self.WithdrawQuota=float(i_tuple[22])
self.Reserve=float(i_tuple[23])
self.TradingDay=self._to_bytes(i_tuple[24])
self.SettlementID=int(i_tuple[25])
self.Credit=float(i_tuple[26])
self.Mortgage=float(i_tuple[27])
self.ExchangeMargin=float(i_tuple[28])
self.DeliveryMargin=float(i_tuple[29])
self.ExchangeDeliveryMargin=float(i_tuple[30])
self.ReserveBalance=float(i_tuple[31])
self.CurrencyID=self._to_bytes(i_tuple[32])
self.PreFundMortgageIn=float(i_tuple[33])
self.PreFundMortgageOut=float(i_tuple[34])
self.FundMortgageIn=float(i_tuple[35])
self.FundMortgageOut=float(i_tuple[36])
self.FundMortgageAvailable=float(i_tuple[37])
self.MortgageableFund=float(i_tuple[38])
self.SpecProductMargin=float(i_tuple[39])
self.SpecProductFrozenMargin=float(i_tuple[40])
self.SpecProductCommission=float(i_tuple[41])
self.SpecProductFrozenCommission=float(i_tuple[42])
self.SpecProductPositionProfit=float(i_tuple[43])
self.SpecProductCloseProfit=float(i_tuple[44])
self.SpecProductPositionProfitByAlg=float(i_tuple[45])
self.SpecProductExchangeMargin=float(i_tuple[46])
self.BizType=self._to_bytes(i_tuple[47])
self.FrozenSwap=float(i_tuple[48])
self.RemainSwap=float(i_tuple[49])
class InvestorPositionField(Base):
"""投资者持仓"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('PosiDirection',ctypes.c_char)# 持仓多空方向
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('PositionDate',ctypes.c_char)# 持仓日期
,('YdPosition',ctypes.c_int)# 上日持仓
,('Position',ctypes.c_int)# 今日持仓
,('LongFrozen',ctypes.c_int)# 多头冻结
,('ShortFrozen',ctypes.c_int)# 空头冻结
,('LongFrozenAmount',ctypes.c_double)# 开仓冻结金额
,('ShortFrozenAmount',ctypes.c_double)# 开仓冻结金额
,('OpenVolume',ctypes.c_int)# 开仓量
,('CloseVolume',ctypes.c_int)# 平仓量
,('OpenAmount',ctypes.c_double)# 开仓金额
,('CloseAmount',ctypes.c_double)# 平仓金额
,('PositionCost',ctypes.c_double)# 持仓成本
,('PreMargin',ctypes.c_double)# 上次占用的保证金
,('UseMargin',ctypes.c_double)# 占用的保证金
,('FrozenMargin',ctypes.c_double)# 冻结的保证金
,('FrozenCash',ctypes.c_double)# 冻结的资金
,('FrozenCommission',ctypes.c_double)# 冻结的手续费
,('CashIn',ctypes.c_double)# 资金差额
,('Commission',ctypes.c_double)# 手续费
,('CloseProfit',ctypes.c_double)# 平仓盈亏
,('PositionProfit',ctypes.c_double)# 持仓盈亏
,('PreSettlementPrice',ctypes.c_double)# 上次结算价
,('SettlementPrice',ctypes.c_double)# 本次结算价
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('OpenCost',ctypes.c_double)# 开仓成本
,('ExchangeMargin',ctypes.c_double)# 交易所保证金
,('CombPosition',ctypes.c_int)# 组合成交形成的持仓
,('CombLongFrozen',ctypes.c_int)# 组合多头冻结
,('CombShortFrozen',ctypes.c_int)# 组合空头冻结
,('CloseProfitByDate',ctypes.c_double)# 逐日盯市平仓盈亏
,('CloseProfitByTrade',ctypes.c_double)# 逐笔对冲平仓盈亏
,('TodayPosition',ctypes.c_int)# 今日持仓
,('MarginRateByMoney',ctypes.c_double)# 保证金率
,('MarginRateByVolume',ctypes.c_double)# 保证金率(按手数)
,('StrikeFrozen',ctypes.c_int)# 执行冻结
,('StrikeFrozenAmount',ctypes.c_double)# 执行冻结金额
,('AbandonFrozen',ctypes.c_int)# 放弃执行冻结
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('YdStrikeFrozen',ctypes.c_int)# 执行冻结的昨仓
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,InstrumentID= '',BrokerID='',InvestorID='',PosiDirection='',HedgeFlag='',PositionDate='',YdPosition=0,Position=0,LongFrozen=0,ShortFrozen=0,LongFrozenAmount=0.0,ShortFrozenAmount=0.0,OpenVolume=0,CloseVolume=0,OpenAmount=0.0,CloseAmount=0.0,PositionCost=0.0,PreMargin=0.0,UseMargin=0.0,FrozenMargin=0.0,FrozenCash=0.0,FrozenCommission=0.0,CashIn=0.0,Commission=0.0,CloseProfit=0.0,PositionProfit=0.0,PreSettlementPrice=0.0,SettlementPrice=0.0,TradingDay='',SettlementID=0,OpenCost=0.0,ExchangeMargin=0.0,CombPosition=0,CombLongFrozen=0,CombShortFrozen=0,CloseProfitByDate=0.0,CloseProfitByTrade=0.0,TodayPosition=0,MarginRateByMoney=0.0,MarginRateByVolume=0.0,StrikeFrozen=0,StrikeFrozenAmount=0.0,AbandonFrozen=0,ExchangeID='',YdStrikeFrozen=0,InvestUnitID=''):
super(InvestorPositionField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.PosiDirection=self._to_bytes(PosiDirection)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.PositionDate=self._to_bytes(PositionDate)
self.YdPosition=int(YdPosition)
self.Position=int(Position)
self.LongFrozen=int(LongFrozen)
self.ShortFrozen=int(ShortFrozen)
self.LongFrozenAmount=float(LongFrozenAmount)
self.ShortFrozenAmount=float(ShortFrozenAmount)
self.OpenVolume=int(OpenVolume)
self.CloseVolume=int(CloseVolume)
self.OpenAmount=float(OpenAmount)
self.CloseAmount=float(CloseAmount)
self.PositionCost=float(PositionCost)
self.PreMargin=float(PreMargin)
self.UseMargin=float(UseMargin)
self.FrozenMargin=float(FrozenMargin)
self.FrozenCash=float(FrozenCash)
self.FrozenCommission=float(FrozenCommission)
self.CashIn=float(CashIn)
self.Commission=float(Commission)
self.CloseProfit=float(CloseProfit)
self.PositionProfit=float(PositionProfit)
self.PreSettlementPrice=float(PreSettlementPrice)
self.SettlementPrice=float(SettlementPrice)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.OpenCost=float(OpenCost)
self.ExchangeMargin=float(ExchangeMargin)
self.CombPosition=int(CombPosition)
self.CombLongFrozen=int(CombLongFrozen)
self.CombShortFrozen=int(CombShortFrozen)
self.CloseProfitByDate=float(CloseProfitByDate)
self.CloseProfitByTrade=float(CloseProfitByTrade)
self.TodayPosition=int(TodayPosition)
self.MarginRateByMoney=float(MarginRateByMoney)
self.MarginRateByVolume=float(MarginRateByVolume)
self.StrikeFrozen=int(StrikeFrozen)
self.StrikeFrozenAmount=float(StrikeFrozenAmount)
self.AbandonFrozen=int(AbandonFrozen)
self.ExchangeID=self._to_bytes(ExchangeID)
self.YdStrikeFrozen=int(YdStrikeFrozen)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.BrokerID=self._to_bytes(i_tuple[2])
self.InvestorID=self._to_bytes(i_tuple[3])
self.PosiDirection=self._to_bytes(i_tuple[4])
self.HedgeFlag=self._to_bytes(i_tuple[5])
self.PositionDate=self._to_bytes(i_tuple[6])
self.YdPosition=int(i_tuple[7])
self.Position=int(i_tuple[8])
self.LongFrozen=int(i_tuple[9])
self.ShortFrozen=int(i_tuple[10])
self.LongFrozenAmount=float(i_tuple[11])
self.ShortFrozenAmount=float(i_tuple[12])
self.OpenVolume=int(i_tuple[13])
self.CloseVolume=int(i_tuple[14])
self.OpenAmount=float(i_tuple[15])
self.CloseAmount=float(i_tuple[16])
self.PositionCost=float(i_tuple[17])
self.PreMargin=float(i_tuple[18])
self.UseMargin=float(i_tuple[19])
self.FrozenMargin=float(i_tuple[20])
self.FrozenCash=float(i_tuple[21])
self.FrozenCommission=float(i_tuple[22])
self.CashIn=float(i_tuple[23])
self.Commission=float(i_tuple[24])
self.CloseProfit=float(i_tuple[25])
self.PositionProfit=float(i_tuple[26])
self.PreSettlementPrice=float(i_tuple[27])
self.SettlementPrice=float(i_tuple[28])
self.TradingDay=self._to_bytes(i_tuple[29])
self.SettlementID=int(i_tuple[30])
self.OpenCost=float(i_tuple[31])
self.ExchangeMargin=float(i_tuple[32])
self.CombPosition=int(i_tuple[33])
self.CombLongFrozen=int(i_tuple[34])
self.CombShortFrozen=int(i_tuple[35])
self.CloseProfitByDate=float(i_tuple[36])
self.CloseProfitByTrade=float(i_tuple[37])
self.TodayPosition=int(i_tuple[38])
self.MarginRateByMoney=float(i_tuple[39])
self.MarginRateByVolume=float(i_tuple[40])
self.StrikeFrozen=int(i_tuple[41])
self.StrikeFrozenAmount=float(i_tuple[42])
self.AbandonFrozen=int(i_tuple[43])
self.ExchangeID=self._to_bytes(i_tuple[44])
self.YdStrikeFrozen=int(i_tuple[45])
self.InvestUnitID=self._to_bytes(i_tuple[46])
class InstrumentMarginRateField(Base):
"""合约保证金率"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('LongMarginRatioByMoney',ctypes.c_double)# 多头保证金率
,('LongMarginRatioByVolume',ctypes.c_double)# 多头保证金费
,('ShortMarginRatioByMoney',ctypes.c_double)# 空头保证金率
,('ShortMarginRatioByVolume',ctypes.c_double)# 空头保证金费
,('IsRelative',ctypes.c_int)# 是否相对交易所收取
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,InstrumentID= '',InvestorRange='',BrokerID='',InvestorID='',HedgeFlag='',LongMarginRatioByMoney=0.0,LongMarginRatioByVolume=0.0,ShortMarginRatioByMoney=0.0,ShortMarginRatioByVolume=0.0,IsRelative=0,ExchangeID='',InvestUnitID=''):
super(InstrumentMarginRateField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.LongMarginRatioByMoney=float(LongMarginRatioByMoney)
self.LongMarginRatioByVolume=float(LongMarginRatioByVolume)
self.ShortMarginRatioByMoney=float(ShortMarginRatioByMoney)
self.ShortMarginRatioByVolume=float(ShortMarginRatioByVolume)
self.IsRelative=int(IsRelative)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.InvestorID=self._to_bytes(i_tuple[4])
self.HedgeFlag=self._to_bytes(i_tuple[5])
self.LongMarginRatioByMoney=float(i_tuple[6])
self.LongMarginRatioByVolume=float(i_tuple[7])
self.ShortMarginRatioByMoney=float(i_tuple[8])
self.ShortMarginRatioByVolume=float(i_tuple[9])
self.IsRelative=int(i_tuple[10])
self.ExchangeID=self._to_bytes(i_tuple[11])
self.InvestUnitID=self._to_bytes(i_tuple[12])
class InstrumentCommissionRateField(Base):
"""合约手续费率"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('OpenRatioByMoney',ctypes.c_double)# 开仓手续费率
,('OpenRatioByVolume',ctypes.c_double)# 开仓手续费
,('CloseRatioByMoney',ctypes.c_double)# 平仓手续费率
,('CloseRatioByVolume',ctypes.c_double)# 平仓手续费
,('CloseTodayRatioByMoney',ctypes.c_double)# 平今手续费率
,('CloseTodayRatioByVolume',ctypes.c_double)# 平今手续费
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('BizType',ctypes.c_char)# 业务类型
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,InstrumentID= '',InvestorRange='',BrokerID='',InvestorID='',OpenRatioByMoney=0.0,OpenRatioByVolume=0.0,CloseRatioByMoney=0.0,CloseRatioByVolume=0.0,CloseTodayRatioByMoney=0.0,CloseTodayRatioByVolume=0.0,ExchangeID='',BizType='',InvestUnitID=''):
super(InstrumentCommissionRateField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.OpenRatioByMoney=float(OpenRatioByMoney)
self.OpenRatioByVolume=float(OpenRatioByVolume)
self.CloseRatioByMoney=float(CloseRatioByMoney)
self.CloseRatioByVolume=float(CloseRatioByVolume)
self.CloseTodayRatioByMoney=float(CloseTodayRatioByMoney)
self.CloseTodayRatioByVolume=float(CloseTodayRatioByVolume)
self.ExchangeID=self._to_bytes(ExchangeID)
self.BizType=self._to_bytes(BizType)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.InvestorID=self._to_bytes(i_tuple[4])
self.OpenRatioByMoney=float(i_tuple[5])
self.OpenRatioByVolume=float(i_tuple[6])
self.CloseRatioByMoney=float(i_tuple[7])
self.CloseRatioByVolume=float(i_tuple[8])
self.CloseTodayRatioByMoney=float(i_tuple[9])
self.CloseTodayRatioByVolume=float(i_tuple[10])
self.ExchangeID=self._to_bytes(i_tuple[11])
self.BizType=self._to_bytes(i_tuple[12])
self.InvestUnitID=self._to_bytes(i_tuple[13])
class DepthMarketDataField(Base):
"""深度行情"""
_fields_ = [
('TradingDay',ctypes.c_char*9)# ///交易日
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('LastPrice',ctypes.c_double)# 最新价
,('PreSettlementPrice',ctypes.c_double)# 上次结算价
,('PreClosePrice',ctypes.c_double)# 昨收盘
,('PreOpenInterest',ctypes.c_double)# 昨持仓量
,('OpenPrice',ctypes.c_double)# 今开盘
,('HighestPrice',ctypes.c_double)# 最高价
,('LowestPrice',ctypes.c_double)# 最低价
,('Volume',ctypes.c_int)# 数量
,('Turnover',ctypes.c_double)# 成交金额
,('OpenInterest',ctypes.c_double)# 持仓量
,('ClosePrice',ctypes.c_double)# 今收盘
,('SettlementPrice',ctypes.c_double)# 本次结算价
,('UpperLimitPrice',ctypes.c_double)# 涨停板价
,('LowerLimitPrice',ctypes.c_double)# 跌停板价
,('PreDelta',ctypes.c_double)# 昨虚实度
,('CurrDelta',ctypes.c_double)# 今虚实度
,('UpdateTime',ctypes.c_char*9)# 最后修改时间
,('UpdateMillisec',ctypes.c_int)# 最后修改毫秒
,('BidPrice1',ctypes.c_double)# 申买价一
,('BidVolume1',ctypes.c_int)# 申买量一
,('AskPrice1',ctypes.c_double)# 申卖价一
,('AskVolume1',ctypes.c_int)# 申卖量一
,('BidPrice2',ctypes.c_double)# 申买价二
,('BidVolume2',ctypes.c_int)# 申买量二
,('AskPrice2',ctypes.c_double)# 申卖价二
,('AskVolume2',ctypes.c_int)# 申卖量二
,('BidPrice3',ctypes.c_double)# 申买价三
,('BidVolume3',ctypes.c_int)# 申买量三
,('AskPrice3',ctypes.c_double)# 申卖价三
,('AskVolume3',ctypes.c_int)# 申卖量三
,('BidPrice4',ctypes.c_double)# 申买价四
,('BidVolume4',ctypes.c_int)# 申买量四
,('AskPrice4',ctypes.c_double)# 申卖价四
,('AskVolume4',ctypes.c_int)# 申卖量四
,('BidPrice5',ctypes.c_double)# 申买价五
,('BidVolume5',ctypes.c_int)# 申买量五
,('AskPrice5',ctypes.c_double)# 申卖价五
,('AskVolume5',ctypes.c_int)# 申卖量五
,('AveragePrice',ctypes.c_double)# 当日均价
,('ActionDay',ctypes.c_char*9)# 业务日期
]
def __init__(self,TradingDay= '',InstrumentID='',ExchangeID='',ExchangeInstID='',LastPrice=0.0,PreSettlementPrice=0.0,PreClosePrice=0.0,PreOpenInterest=0.0,OpenPrice=0.0,HighestPrice=0.0,LowestPrice=0.0,Volume=0,Turnover=0.0,OpenInterest=0.0,ClosePrice=0.0,SettlementPrice=0.0,UpperLimitPrice=0.0,LowerLimitPrice=0.0,PreDelta=0.0,CurrDelta=0.0,UpdateTime='',UpdateMillisec=0,BidPrice1=0.0,BidVolume1=0,AskPrice1=0.0,AskVolume1=0,BidPrice2=0.0,BidVolume2=0,AskPrice2=0.0,AskVolume2=0,BidPrice3=0.0,BidVolume3=0,AskPrice3=0.0,AskVolume3=0,BidPrice4=0.0,BidVolume4=0,AskPrice4=0.0,AskVolume4=0,BidPrice5=0.0,BidVolume5=0,AskPrice5=0.0,AskVolume5=0,AveragePrice=0.0,ActionDay=''):
super(DepthMarketDataField,self).__init__()
self.TradingDay=self._to_bytes(TradingDay)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.LastPrice=float(LastPrice)
self.PreSettlementPrice=float(PreSettlementPrice)
self.PreClosePrice=float(PreClosePrice)
self.PreOpenInterest=float(PreOpenInterest)
self.OpenPrice=float(OpenPrice)
self.HighestPrice=float(HighestPrice)
self.LowestPrice=float(LowestPrice)
self.Volume=int(Volume)
self.Turnover=float(Turnover)
self.OpenInterest=float(OpenInterest)
self.ClosePrice=float(ClosePrice)
self.SettlementPrice=float(SettlementPrice)
self.UpperLimitPrice=float(UpperLimitPrice)
self.LowerLimitPrice=float(LowerLimitPrice)
self.PreDelta=float(PreDelta)
self.CurrDelta=float(CurrDelta)
self.UpdateTime=self._to_bytes(UpdateTime)
self.UpdateMillisec=int(UpdateMillisec)
self.BidPrice1=float(BidPrice1)
self.BidVolume1=int(BidVolume1)
self.AskPrice1=float(AskPrice1)
self.AskVolume1=int(AskVolume1)
self.BidPrice2=float(BidPrice2)
self.BidVolume2=int(BidVolume2)
self.AskPrice2=float(AskPrice2)
self.AskVolume2=int(AskVolume2)
self.BidPrice3=float(BidPrice3)
self.BidVolume3=int(BidVolume3)
self.AskPrice3=float(AskPrice3)
self.AskVolume3=int(AskVolume3)
self.BidPrice4=float(BidPrice4)
self.BidVolume4=int(BidVolume4)
self.AskPrice4=float(AskPrice4)
self.AskVolume4=int(AskVolume4)
self.BidPrice5=float(BidPrice5)
self.BidVolume5=int(BidVolume5)
self.AskPrice5=float(AskPrice5)
self.AskVolume5=int(AskVolume5)
self.AveragePrice=float(AveragePrice)
self.ActionDay=self._to_bytes(ActionDay)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradingDay=self._to_bytes(i_tuple[1])
self.InstrumentID=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
self.ExchangeInstID=self._to_bytes(i_tuple[4])
self.LastPrice=float(i_tuple[5])
self.PreSettlementPrice=float(i_tuple[6])
self.PreClosePrice=float(i_tuple[7])
self.PreOpenInterest=float(i_tuple[8])
self.OpenPrice=float(i_tuple[9])
self.HighestPrice=float(i_tuple[10])
self.LowestPrice=float(i_tuple[11])
self.Volume=int(i_tuple[12])
self.Turnover=float(i_tuple[13])
self.OpenInterest=float(i_tuple[14])
self.ClosePrice=float(i_tuple[15])
self.SettlementPrice=float(i_tuple[16])
self.UpperLimitPrice=float(i_tuple[17])
self.LowerLimitPrice=float(i_tuple[18])
self.PreDelta=float(i_tuple[19])
self.CurrDelta=float(i_tuple[20])
self.UpdateTime=self._to_bytes(i_tuple[21])
self.UpdateMillisec=int(i_tuple[22])
self.BidPrice1=float(i_tuple[23])
self.BidVolume1=int(i_tuple[24])
self.AskPrice1=float(i_tuple[25])
self.AskVolume1=int(i_tuple[26])
self.BidPrice2=float(i_tuple[27])
self.BidVolume2=int(i_tuple[28])
self.AskPrice2=float(i_tuple[29])
self.AskVolume2=int(i_tuple[30])
self.BidPrice3=float(i_tuple[31])
self.BidVolume3=int(i_tuple[32])
self.AskPrice3=float(i_tuple[33])
self.AskVolume3=int(i_tuple[34])
self.BidPrice4=float(i_tuple[35])
self.BidVolume4=int(i_tuple[36])
self.AskPrice4=float(i_tuple[37])
self.AskVolume4=int(i_tuple[38])
self.BidPrice5=float(i_tuple[39])
self.BidVolume5=int(i_tuple[40])
self.AskPrice5=float(i_tuple[41])
self.AskVolume5=int(i_tuple[42])
self.AveragePrice=float(i_tuple[43])
self.ActionDay=self._to_bytes(i_tuple[44])
class InstrumentTradingRightField(Base):
"""投资者合约交易权限"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('TradingRight',ctypes.c_char)# 交易权限
]
def __init__(self,InstrumentID= '',InvestorRange='',BrokerID='',InvestorID='',TradingRight=''):
super(InstrumentTradingRightField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.TradingRight=self._to_bytes(TradingRight)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.InvestorID=self._to_bytes(i_tuple[4])
self.TradingRight=self._to_bytes(i_tuple[5])
class BrokerUserField(Base):
"""经纪公司用户"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('UserName',ctypes.c_char*81)# 用户名称
,('UserType',ctypes.c_char)# 用户类型
,('IsActive',ctypes.c_int)# 是否活跃
,('IsUsingOTP',ctypes.c_int)# 是否使用令牌
,('IsAuthForce',ctypes.c_int)# 是否强制终端认证
]
def __init__(self,BrokerID= '',UserID='',UserName='',UserType='',IsActive=0,IsUsingOTP=0,IsAuthForce=0):
super(BrokerUserField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.UserName=self._to_bytes(UserName)
self.UserType=self._to_bytes(UserType)
self.IsActive=int(IsActive)
self.IsUsingOTP=int(IsUsingOTP)
self.IsAuthForce=int(IsAuthForce)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
self.UserName=self._to_bytes(i_tuple[3])
self.UserType=self._to_bytes(i_tuple[4])
self.IsActive=int(i_tuple[5])
self.IsUsingOTP=int(i_tuple[6])
self.IsAuthForce=int(i_tuple[7])
class BrokerUserPasswordField(Base):
"""经纪公司用户口令"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('Password',ctypes.c_char*41)# 密码
,('LastUpdateTime',ctypes.c_char*17)# 上次修改时间
,('LastLoginTime',ctypes.c_char*17)# 上次登陆时间
,('ExpireDate',ctypes.c_char*9)# 密码过期时间
,('WeakExpireDate',ctypes.c_char*9)# 弱密码过期时间
]
def __init__(self,BrokerID= '',UserID='',Password='',LastUpdateTime='',LastLoginTime='',ExpireDate='',WeakExpireDate=''):
super(BrokerUserPasswordField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.Password=self._to_bytes(Password)
self.LastUpdateTime=self._to_bytes(LastUpdateTime)
self.LastLoginTime=self._to_bytes(LastLoginTime)
self.ExpireDate=self._to_bytes(ExpireDate)
self.WeakExpireDate=self._to_bytes(WeakExpireDate)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
self.Password=self._to_bytes(i_tuple[3])
self.LastUpdateTime=self._to_bytes(i_tuple[4])
self.LastLoginTime=self._to_bytes(i_tuple[5])
self.ExpireDate=self._to_bytes(i_tuple[6])
self.WeakExpireDate=self._to_bytes(i_tuple[7])
class BrokerUserFunctionField(Base):
"""经纪公司用户功能权限"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('BrokerFunctionCode',ctypes.c_char)# 经纪公司功能代码
]
def __init__(self,BrokerID= '',UserID='',BrokerFunctionCode=''):
super(BrokerUserFunctionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.BrokerFunctionCode=self._to_bytes(BrokerFunctionCode)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
self.BrokerFunctionCode=self._to_bytes(i_tuple[3])
class TraderOfferField(Base):
"""交易所交易员报盘机"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('Password',ctypes.c_char*41)# 密码
,('InstallID',ctypes.c_int)# 安装编号
,('OrderLocalID',ctypes.c_char*13)# 本地报单编号
,('TraderConnectStatus',ctypes.c_char)# 交易所交易员连接状态
,('ConnectRequestDate',ctypes.c_char*9)# 发出连接请求的日期
,('ConnectRequestTime',ctypes.c_char*9)# 发出连接请求的时间
,('LastReportDate',ctypes.c_char*9)# 上次报告日期
,('LastReportTime',ctypes.c_char*9)# 上次报告时间
,('ConnectDate',ctypes.c_char*9)# 完成连接日期
,('ConnectTime',ctypes.c_char*9)# 完成连接时间
,('StartDate',ctypes.c_char*9)# 启动日期
,('StartTime',ctypes.c_char*9)# 启动时间
,('TradingDay',ctypes.c_char*9)# 交易日
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('MaxTradeID',ctypes.c_char*21)# 本席位最大成交编号
,('MaxOrderMessageReference',ctypes.c_char*7)# 本席位最大报单备拷
]
def __init__(self,ExchangeID= '',TraderID='',ParticipantID='',Password='',InstallID=0,OrderLocalID='',TraderConnectStatus='',ConnectRequestDate='',ConnectRequestTime='',LastReportDate='',LastReportTime='',ConnectDate='',ConnectTime='',StartDate='',StartTime='',TradingDay='',BrokerID='',MaxTradeID='',MaxOrderMessageReference=''):
super(TraderOfferField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.TraderID=self._to_bytes(TraderID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.Password=self._to_bytes(Password)
self.InstallID=int(InstallID)
self.OrderLocalID=self._to_bytes(OrderLocalID)
self.TraderConnectStatus=self._to_bytes(TraderConnectStatus)
self.ConnectRequestDate=self._to_bytes(ConnectRequestDate)
self.ConnectRequestTime=self._to_bytes(ConnectRequestTime)
self.LastReportDate=self._to_bytes(LastReportDate)
self.LastReportTime=self._to_bytes(LastReportTime)
self.ConnectDate=self._to_bytes(ConnectDate)
self.ConnectTime=self._to_bytes(ConnectTime)
self.StartDate=self._to_bytes(StartDate)
self.StartTime=self._to_bytes(StartTime)
self.TradingDay=self._to_bytes(TradingDay)
self.BrokerID=self._to_bytes(BrokerID)
self.MaxTradeID=self._to_bytes(MaxTradeID)
self.MaxOrderMessageReference=self._to_bytes(MaxOrderMessageReference)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.TraderID=self._to_bytes(i_tuple[2])
self.ParticipantID=self._to_bytes(i_tuple[3])
self.Password=self._to_bytes(i_tuple[4])
self.InstallID=int(i_tuple[5])
self.OrderLocalID=self._to_bytes(i_tuple[6])
self.TraderConnectStatus=self._to_bytes(i_tuple[7])
self.ConnectRequestDate=self._to_bytes(i_tuple[8])
self.ConnectRequestTime=self._to_bytes(i_tuple[9])
self.LastReportDate=self._to_bytes(i_tuple[10])
self.LastReportTime=self._to_bytes(i_tuple[11])
self.ConnectDate=self._to_bytes(i_tuple[12])
self.ConnectTime=self._to_bytes(i_tuple[13])
self.StartDate=self._to_bytes(i_tuple[14])
self.StartTime=self._to_bytes(i_tuple[15])
self.TradingDay=self._to_bytes(i_tuple[16])
self.BrokerID=self._to_bytes(i_tuple[17])
self.MaxTradeID=self._to_bytes(i_tuple[18])
self.MaxOrderMessageReference=self._to_bytes(i_tuple[19])
class SettlementInfoField(Base):
"""投资者结算结果"""
_fields_ = [
('TradingDay',ctypes.c_char*9)# ///交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('SequenceNo',ctypes.c_int)# 序号
,('Content',ctypes.c_char*501)# 消息正文
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('CurrencyID',ctypes.c_char*4)# 币种代码
]
def __init__(self,TradingDay= '',SettlementID=0,BrokerID='',InvestorID='',SequenceNo=0,Content='',AccountID='',CurrencyID=''):
super(SettlementInfoField,self).__init__()
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.SequenceNo=int(SequenceNo)
self.Content=self._to_bytes(Content)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradingDay=self._to_bytes(i_tuple[1])
self.SettlementID=int(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.InvestorID=self._to_bytes(i_tuple[4])
self.SequenceNo=int(i_tuple[5])
self.Content=self._to_bytes(i_tuple[6])
self.AccountID=self._to_bytes(i_tuple[7])
self.CurrencyID=self._to_bytes(i_tuple[8])
class InstrumentMarginRateAdjustField(Base):
"""合约保证金率调整"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('LongMarginRatioByMoney',ctypes.c_double)# 多头保证金率
,('LongMarginRatioByVolume',ctypes.c_double)# 多头保证金费
,('ShortMarginRatioByMoney',ctypes.c_double)# 空头保证金率
,('ShortMarginRatioByVolume',ctypes.c_double)# 空头保证金费
,('IsRelative',ctypes.c_int)# 是否相对交易所收取
]
def __init__(self,InstrumentID= '',InvestorRange='',BrokerID='',InvestorID='',HedgeFlag='',LongMarginRatioByMoney=0.0,LongMarginRatioByVolume=0.0,ShortMarginRatioByMoney=0.0,ShortMarginRatioByVolume=0.0,IsRelative=0):
super(InstrumentMarginRateAdjustField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.LongMarginRatioByMoney=float(LongMarginRatioByMoney)
self.LongMarginRatioByVolume=float(LongMarginRatioByVolume)
self.ShortMarginRatioByMoney=float(ShortMarginRatioByMoney)
self.ShortMarginRatioByVolume=float(ShortMarginRatioByVolume)
self.IsRelative=int(IsRelative)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.InvestorID=self._to_bytes(i_tuple[4])
self.HedgeFlag=self._to_bytes(i_tuple[5])
self.LongMarginRatioByMoney=float(i_tuple[6])
self.LongMarginRatioByVolume=float(i_tuple[7])
self.ShortMarginRatioByMoney=float(i_tuple[8])
self.ShortMarginRatioByVolume=float(i_tuple[9])
self.IsRelative=int(i_tuple[10])
class ExchangeMarginRateField(Base):
"""交易所保证金率"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('LongMarginRatioByMoney',ctypes.c_double)# 多头保证金率
,('LongMarginRatioByVolume',ctypes.c_double)# 多头保证金费
,('ShortMarginRatioByMoney',ctypes.c_double)# 空头保证金率
,('ShortMarginRatioByVolume',ctypes.c_double)# 空头保证金费
,('ExchangeID',ctypes.c_char*9)# 交易所代码
]
def __init__(self,BrokerID= '',InstrumentID='',HedgeFlag='',LongMarginRatioByMoney=0.0,LongMarginRatioByVolume=0.0,ShortMarginRatioByMoney=0.0,ShortMarginRatioByVolume=0.0,ExchangeID=''):
super(ExchangeMarginRateField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.LongMarginRatioByMoney=float(LongMarginRatioByMoney)
self.LongMarginRatioByVolume=float(LongMarginRatioByVolume)
self.ShortMarginRatioByMoney=float(ShortMarginRatioByMoney)
self.ShortMarginRatioByVolume=float(ShortMarginRatioByVolume)
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InstrumentID=self._to_bytes(i_tuple[2])
self.HedgeFlag=self._to_bytes(i_tuple[3])
self.LongMarginRatioByMoney=float(i_tuple[4])
self.LongMarginRatioByVolume=float(i_tuple[5])
self.ShortMarginRatioByMoney=float(i_tuple[6])
self.ShortMarginRatioByVolume=float(i_tuple[7])
self.ExchangeID=self._to_bytes(i_tuple[8])
class ExchangeMarginRateAdjustField(Base):
"""交易所保证金率调整"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('LongMarginRatioByMoney',ctypes.c_double)# 跟随交易所投资者多头保证金率
,('LongMarginRatioByVolume',ctypes.c_double)# 跟随交易所投资者多头保证金费
,('ShortMarginRatioByMoney',ctypes.c_double)# 跟随交易所投资者空头保证金率
,('ShortMarginRatioByVolume',ctypes.c_double)# 跟随交易所投资者空头保证金费
,('ExchLongMarginRatioByMoney',ctypes.c_double)# 交易所多头保证金率
,('ExchLongMarginRatioByVolume',ctypes.c_double)# 交易所多头保证金费
,('ExchShortMarginRatioByMoney',ctypes.c_double)# 交易所空头保证金率
,('ExchShortMarginRatioByVolume',ctypes.c_double)# 交易所空头保证金费
,('NoLongMarginRatioByMoney',ctypes.c_double)# 不跟随交易所投资者多头保证金率
,('NoLongMarginRatioByVolume',ctypes.c_double)# 不跟随交易所投资者多头保证金费
,('NoShortMarginRatioByMoney',ctypes.c_double)# 不跟随交易所投资者空头保证金率
,('NoShortMarginRatioByVolume',ctypes.c_double)# 不跟随交易所投资者空头保证金费
]
def __init__(self,BrokerID= '',InstrumentID='',HedgeFlag='',LongMarginRatioByMoney=0.0,LongMarginRatioByVolume=0.0,ShortMarginRatioByMoney=0.0,ShortMarginRatioByVolume=0.0,ExchLongMarginRatioByMoney=0.0,ExchLongMarginRatioByVolume=0.0,ExchShortMarginRatioByMoney=0.0,ExchShortMarginRatioByVolume=0.0,NoLongMarginRatioByMoney=0.0,NoLongMarginRatioByVolume=0.0,NoShortMarginRatioByMoney=0.0,NoShortMarginRatioByVolume=0.0):
super(ExchangeMarginRateAdjustField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.LongMarginRatioByMoney=float(LongMarginRatioByMoney)
self.LongMarginRatioByVolume=float(LongMarginRatioByVolume)
self.ShortMarginRatioByMoney=float(ShortMarginRatioByMoney)
self.ShortMarginRatioByVolume=float(ShortMarginRatioByVolume)
self.ExchLongMarginRatioByMoney=float(ExchLongMarginRatioByMoney)
self.ExchLongMarginRatioByVolume=float(ExchLongMarginRatioByVolume)
self.ExchShortMarginRatioByMoney=float(ExchShortMarginRatioByMoney)
self.ExchShortMarginRatioByVolume=float(ExchShortMarginRatioByVolume)
self.NoLongMarginRatioByMoney=float(NoLongMarginRatioByMoney)
self.NoLongMarginRatioByVolume=float(NoLongMarginRatioByVolume)
self.NoShortMarginRatioByMoney=float(NoShortMarginRatioByMoney)
self.NoShortMarginRatioByVolume=float(NoShortMarginRatioByVolume)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InstrumentID=self._to_bytes(i_tuple[2])
self.HedgeFlag=self._to_bytes(i_tuple[3])
self.LongMarginRatioByMoney=float(i_tuple[4])
self.LongMarginRatioByVolume=float(i_tuple[5])
self.ShortMarginRatioByMoney=float(i_tuple[6])
self.ShortMarginRatioByVolume=float(i_tuple[7])
self.ExchLongMarginRatioByMoney=float(i_tuple[8])
self.ExchLongMarginRatioByVolume=float(i_tuple[9])
self.ExchShortMarginRatioByMoney=float(i_tuple[10])
self.ExchShortMarginRatioByVolume=float(i_tuple[11])
self.NoLongMarginRatioByMoney=float(i_tuple[12])
self.NoLongMarginRatioByVolume=float(i_tuple[13])
self.NoShortMarginRatioByMoney=float(i_tuple[14])
self.NoShortMarginRatioByVolume=float(i_tuple[15])
class ExchangeRateField(Base):
"""汇率"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('FromCurrencyID',ctypes.c_char*4)# 源币种
,('FromCurrencyUnit',ctypes.c_double)# 源币种单位数量
,('ToCurrencyID',ctypes.c_char*4)# 目标币种
,('ExchangeRate',ctypes.c_double)# 汇率
]
def __init__(self,BrokerID= '',FromCurrencyID='',FromCurrencyUnit=0.0,ToCurrencyID='',ExchangeRate=0.0):
super(ExchangeRateField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.FromCurrencyID=self._to_bytes(FromCurrencyID)
self.FromCurrencyUnit=float(FromCurrencyUnit)
self.ToCurrencyID=self._to_bytes(ToCurrencyID)
self.ExchangeRate=float(ExchangeRate)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.FromCurrencyID=self._to_bytes(i_tuple[2])
self.FromCurrencyUnit=float(i_tuple[3])
self.ToCurrencyID=self._to_bytes(i_tuple[4])
self.ExchangeRate=float(i_tuple[5])
class SettlementRefField(Base):
"""结算引用"""
_fields_ = [
('TradingDay',ctypes.c_char*9)# ///交易日
,('SettlementID',ctypes.c_int)# 结算编号
]
def __init__(self,TradingDay= '',SettlementID=0):
super(SettlementRefField,self).__init__()
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradingDay=self._to_bytes(i_tuple[1])
self.SettlementID=int(i_tuple[2])
class CurrentTimeField(Base):
"""当前时间"""
_fields_ = [
('CurrDate',ctypes.c_char*9)# ///当前日期
,('CurrTime',ctypes.c_char*9)# 当前时间
,('CurrMillisec',ctypes.c_int)# 当前时间(毫秒)
,('ActionDay',ctypes.c_char*9)# 业务日期
]
def __init__(self,CurrDate= '',CurrTime='',CurrMillisec=0,ActionDay=''):
super(CurrentTimeField,self).__init__()
self.CurrDate=self._to_bytes(CurrDate)
self.CurrTime=self._to_bytes(CurrTime)
self.CurrMillisec=int(CurrMillisec)
self.ActionDay=self._to_bytes(ActionDay)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.CurrDate=self._to_bytes(i_tuple[1])
self.CurrTime=self._to_bytes(i_tuple[2])
self.CurrMillisec=int(i_tuple[3])
self.ActionDay=self._to_bytes(i_tuple[4])
class CommPhaseField(Base):
"""通讯阶段"""
_fields_ = [
('TradingDay',ctypes.c_char*9)# ///交易日
,('CommPhaseNo',ctypes.c_short)# 通讯时段编号
,('SystemID',ctypes.c_char*21)# 系统编号
]
def __init__(self,TradingDay= '',CommPhaseNo=0,SystemID=''):
super(CommPhaseField,self).__init__()
self.TradingDay=self._to_bytes(TradingDay)
self.CommPhaseNo=int(CommPhaseNo)
self.SystemID=self._to_bytes(SystemID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradingDay=self._to_bytes(i_tuple[1])
self.CommPhaseNo=int(i_tuple[2])
self.SystemID=self._to_bytes(i_tuple[3])
class LoginInfoField(Base):
"""登录信息"""
_fields_ = [
('FrontID',ctypes.c_int)# ///前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('LoginDate',ctypes.c_char*9)# 登录日期
,('LoginTime',ctypes.c_char*9)# 登录时间
,('IPAddress',ctypes.c_char*16)# IP地址
,('UserProductInfo',ctypes.c_char*11)# 用户端产品信息
,('InterfaceProductInfo',ctypes.c_char*11)# 接口端产品信息
,('ProtocolInfo',ctypes.c_char*11)# 协议信息
,('SystemName',ctypes.c_char*41)# 系统名称
,('PasswordDeprecated',ctypes.c_char*41)# 密码,已弃用
,('MaxOrderRef',ctypes.c_char*13)# 最大报单引用
,('SHFETime',ctypes.c_char*9)# 上期所时间
,('DCETime',ctypes.c_char*9)# 大商所时间
,('CZCETime',ctypes.c_char*9)# 郑商所时间
,('FFEXTime',ctypes.c_char*9)# 中金所时间
,('MacAddress',ctypes.c_char*21)# Mac地址
,('OneTimePassword',ctypes.c_char*41)# 动态密码
,('INETime',ctypes.c_char*9)# 能源中心时间
,('IsQryControl',ctypes.c_int)# 查询时是否需要流控
,('LoginRemark',ctypes.c_char*36)# 登录备注
,('Password',ctypes.c_char*41)# 密码
]
def __init__(self,FrontID= 0,SessionID=0,BrokerID='',UserID='',LoginDate='',LoginTime='',IPAddress='',UserProductInfo='',InterfaceProductInfo='',ProtocolInfo='',SystemName='',PasswordDeprecated='',MaxOrderRef='',SHFETime='',DCETime='',CZCETime='',FFEXTime='',MacAddress='',OneTimePassword='',INETime='',IsQryControl=0,LoginRemark='',Password=''):
super(LoginInfoField,self).__init__()
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.LoginDate=self._to_bytes(LoginDate)
self.LoginTime=self._to_bytes(LoginTime)
self.IPAddress=self._to_bytes(IPAddress)
self.UserProductInfo=self._to_bytes(UserProductInfo)
self.InterfaceProductInfo=self._to_bytes(InterfaceProductInfo)
self.ProtocolInfo=self._to_bytes(ProtocolInfo)
self.SystemName=self._to_bytes(SystemName)
self.PasswordDeprecated=self._to_bytes(PasswordDeprecated)
self.MaxOrderRef=self._to_bytes(MaxOrderRef)
self.SHFETime=self._to_bytes(SHFETime)
self.DCETime=self._to_bytes(DCETime)
self.CZCETime=self._to_bytes(CZCETime)
self.FFEXTime=self._to_bytes(FFEXTime)
self.MacAddress=self._to_bytes(MacAddress)
self.OneTimePassword=self._to_bytes(OneTimePassword)
self.INETime=self._to_bytes(INETime)
self.IsQryControl=int(IsQryControl)
self.LoginRemark=self._to_bytes(LoginRemark)
self.Password=self._to_bytes(Password)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.FrontID=int(i_tuple[1])
self.SessionID=int(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.UserID=self._to_bytes(i_tuple[4])
self.LoginDate=self._to_bytes(i_tuple[5])
self.LoginTime=self._to_bytes(i_tuple[6])
self.IPAddress=self._to_bytes(i_tuple[7])
self.UserProductInfo=self._to_bytes(i_tuple[8])
self.InterfaceProductInfo=self._to_bytes(i_tuple[9])
self.ProtocolInfo=self._to_bytes(i_tuple[10])
self.SystemName=self._to_bytes(i_tuple[11])
self.PasswordDeprecated=self._to_bytes(i_tuple[12])
self.MaxOrderRef=self._to_bytes(i_tuple[13])
self.SHFETime=self._to_bytes(i_tuple[14])
self.DCETime=self._to_bytes(i_tuple[15])
self.CZCETime=self._to_bytes(i_tuple[16])
self.FFEXTime=self._to_bytes(i_tuple[17])
self.MacAddress=self._to_bytes(i_tuple[18])
self.OneTimePassword=self._to_bytes(i_tuple[19])
self.INETime=self._to_bytes(i_tuple[20])
self.IsQryControl=int(i_tuple[21])
self.LoginRemark=self._to_bytes(i_tuple[22])
self.Password=self._to_bytes(i_tuple[23])
class LogoutAllField(Base):
"""登录信息"""
_fields_ = [
('FrontID',ctypes.c_int)# ///前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('SystemName',ctypes.c_char*41)# 系统名称
]
def __init__(self,FrontID= 0,SessionID=0,SystemName=''):
super(LogoutAllField,self).__init__()
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.SystemName=self._to_bytes(SystemName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.FrontID=int(i_tuple[1])
self.SessionID=int(i_tuple[2])
self.SystemName=self._to_bytes(i_tuple[3])
class FrontStatusField(Base):
"""前置状态"""
_fields_ = [
('FrontID',ctypes.c_int)# ///前置编号
,('LastReportDate',ctypes.c_char*9)# 上次报告日期
,('LastReportTime',ctypes.c_char*9)# 上次报告时间
,('IsActive',ctypes.c_int)# 是否活跃
]
def __init__(self,FrontID= 0,LastReportDate='',LastReportTime='',IsActive=0):
super(FrontStatusField,self).__init__()
self.FrontID=int(FrontID)
self.LastReportDate=self._to_bytes(LastReportDate)
self.LastReportTime=self._to_bytes(LastReportTime)
self.IsActive=int(IsActive)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.FrontID=int(i_tuple[1])
self.LastReportDate=self._to_bytes(i_tuple[2])
self.LastReportTime=self._to_bytes(i_tuple[3])
self.IsActive=int(i_tuple[4])
class UserPasswordUpdateField(Base):
"""用户口令变更"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('OldPassword',ctypes.c_char*41)# 原来的口令
,('NewPassword',ctypes.c_char*41)# 新的口令
]
def __init__(self,BrokerID= '',UserID='',OldPassword='',NewPassword=''):
super(UserPasswordUpdateField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.OldPassword=self._to_bytes(OldPassword)
self.NewPassword=self._to_bytes(NewPassword)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
self.OldPassword=self._to_bytes(i_tuple[3])
self.NewPassword=self._to_bytes(i_tuple[4])
class InputOrderField(Base):
"""输入报单"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('OrderRef',ctypes.c_char*13)# 报单引用
,('UserID',ctypes.c_char*16)# 用户代码
,('OrderPriceType',ctypes.c_char)# 报单价格条件
,('Direction',ctypes.c_char)# 买卖方向
,('CombOffsetFlag',ctypes.c_char*5)# 组合开平标志
,('CombHedgeFlag',ctypes.c_char*5)# 组合投机套保标志
,('LimitPrice',ctypes.c_double)# 价格
,('VolumeTotalOriginal',ctypes.c_int)# 数量
,('TimeCondition',ctypes.c_char)# 有效期类型
,('GTDDate',ctypes.c_char*9)# GTD日期
,('VolumeCondition',ctypes.c_char)# 成交量类型
,('MinVolume',ctypes.c_int)# 最小成交量
,('ContingentCondition',ctypes.c_char)# 触发条件
,('StopPrice',ctypes.c_double)# 止损价
,('ForceCloseReason',ctypes.c_char)# 强平原因
,('IsAutoSuspend',ctypes.c_int)# 自动挂起标志
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('RequestID',ctypes.c_int)# 请求编号
,('UserForceClose',ctypes.c_int)# 用户强评标志
,('IsSwapOrder',ctypes.c_int)# 互换单标志
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('AccountID',ctypes.c_char*13)# 资金账号
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('ClientID',ctypes.c_char*11)# 交易编码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',OrderRef='',UserID='',OrderPriceType='',Direction='',CombOffsetFlag='',CombHedgeFlag='',LimitPrice=0.0,VolumeTotalOriginal=0,TimeCondition='',GTDDate='',VolumeCondition='',MinVolume=0,ContingentCondition='',StopPrice=0.0,ForceCloseReason='',IsAutoSuspend=0,BusinessUnit='',RequestID=0,UserForceClose=0,IsSwapOrder=0,ExchangeID='',InvestUnitID='',AccountID='',CurrencyID='',ClientID='',IPAddress='',MacAddress=''):
super(InputOrderField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.OrderRef=self._to_bytes(OrderRef)
self.UserID=self._to_bytes(UserID)
self.OrderPriceType=self._to_bytes(OrderPriceType)
self.Direction=self._to_bytes(Direction)
self.CombOffsetFlag=self._to_bytes(CombOffsetFlag)
self.CombHedgeFlag=self._to_bytes(CombHedgeFlag)
self.LimitPrice=float(LimitPrice)
self.VolumeTotalOriginal=int(VolumeTotalOriginal)
self.TimeCondition=self._to_bytes(TimeCondition)
self.GTDDate=self._to_bytes(GTDDate)
self.VolumeCondition=self._to_bytes(VolumeCondition)
self.MinVolume=int(MinVolume)
self.ContingentCondition=self._to_bytes(ContingentCondition)
self.StopPrice=float(StopPrice)
self.ForceCloseReason=self._to_bytes(ForceCloseReason)
self.IsAutoSuspend=int(IsAutoSuspend)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.RequestID=int(RequestID)
self.UserForceClose=int(UserForceClose)
self.IsSwapOrder=int(IsSwapOrder)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
self.ClientID=self._to_bytes(ClientID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.OrderRef=self._to_bytes(i_tuple[4])
self.UserID=self._to_bytes(i_tuple[5])
self.OrderPriceType=self._to_bytes(i_tuple[6])
self.Direction=self._to_bytes(i_tuple[7])
self.CombOffsetFlag=self._to_bytes(i_tuple[8])
self.CombHedgeFlag=self._to_bytes(i_tuple[9])
self.LimitPrice=float(i_tuple[10])
self.VolumeTotalOriginal=int(i_tuple[11])
self.TimeCondition=self._to_bytes(i_tuple[12])
self.GTDDate=self._to_bytes(i_tuple[13])
self.VolumeCondition=self._to_bytes(i_tuple[14])
self.MinVolume=int(i_tuple[15])
self.ContingentCondition=self._to_bytes(i_tuple[16])
self.StopPrice=float(i_tuple[17])
self.ForceCloseReason=self._to_bytes(i_tuple[18])
self.IsAutoSuspend=int(i_tuple[19])
self.BusinessUnit=self._to_bytes(i_tuple[20])
self.RequestID=int(i_tuple[21])
self.UserForceClose=int(i_tuple[22])
self.IsSwapOrder=int(i_tuple[23])
self.ExchangeID=self._to_bytes(i_tuple[24])
self.InvestUnitID=self._to_bytes(i_tuple[25])
self.AccountID=self._to_bytes(i_tuple[26])
self.CurrencyID=self._to_bytes(i_tuple[27])
self.ClientID=self._to_bytes(i_tuple[28])
self.IPAddress=self._to_bytes(i_tuple[29])
self.MacAddress=self._to_bytes(i_tuple[30])
class OrderField(Base):
"""报单"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('OrderRef',ctypes.c_char*13)# 报单引用
,('UserID',ctypes.c_char*16)# 用户代码
,('OrderPriceType',ctypes.c_char)# 报单价格条件
,('Direction',ctypes.c_char)# 买卖方向
,('CombOffsetFlag',ctypes.c_char*5)# 组合开平标志
,('CombHedgeFlag',ctypes.c_char*5)# 组合投机套保标志
,('LimitPrice',ctypes.c_double)# 价格
,('VolumeTotalOriginal',ctypes.c_int)# 数量
,('TimeCondition',ctypes.c_char)# 有效期类型
,('GTDDate',ctypes.c_char*9)# GTD日期
,('VolumeCondition',ctypes.c_char)# 成交量类型
,('MinVolume',ctypes.c_int)# 最小成交量
,('ContingentCondition',ctypes.c_char)# 触发条件
,('StopPrice',ctypes.c_double)# 止损价
,('ForceCloseReason',ctypes.c_char)# 强平原因
,('IsAutoSuspend',ctypes.c_int)# 自动挂起标志
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('RequestID',ctypes.c_int)# 请求编号
,('OrderLocalID',ctypes.c_char*13)# 本地报单编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('OrderSubmitStatus',ctypes.c_char)# 报单提交状态
,('NotifySequence',ctypes.c_int)# 报单提示序号
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('OrderSysID',ctypes.c_char*21)# 报单编号
,('OrderSource',ctypes.c_char)# 报单来源
,('OrderStatus',ctypes.c_char)# 报单状态
,('OrderType',ctypes.c_char)# 报单类型
,('VolumeTraded',ctypes.c_int)# 今成交数量
,('VolumeTotal',ctypes.c_int)# 剩余数量
,('InsertDate',ctypes.c_char*9)# 报单日期
,('InsertTime',ctypes.c_char*9)# 委托时间
,('ActiveTime',ctypes.c_char*9)# 激活时间
,('SuspendTime',ctypes.c_char*9)# 挂起时间
,('UpdateTime',ctypes.c_char*9)# 最后修改时间
,('CancelTime',ctypes.c_char*9)# 撤销时间
,('ActiveTraderID',ctypes.c_char*21)# 最后修改交易所交易员代码
,('ClearingPartID',ctypes.c_char*11)# 结算会员编号
,('SequenceNo',ctypes.c_int)# 序号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('UserProductInfo',ctypes.c_char*11)# 用户端产品信息
,('StatusMsg',ctypes.c_char*81)# 状态信息
,('UserForceClose',ctypes.c_int)# 用户强评标志
,('ActiveUserID',ctypes.c_char*16)# 操作用户代码
,('BrokerOrderSeq',ctypes.c_int)# 经纪公司报单编号
,('RelativeOrderSysID',ctypes.c_char*21)# 相关报单
,('ZCETotalTradedVolume',ctypes.c_int)# 郑商所成交数量
,('IsSwapOrder',ctypes.c_int)# 互换单标志
,('BranchID',ctypes.c_char*9)# 营业部编号
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('AccountID',ctypes.c_char*13)# 资金账号
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',OrderRef='',UserID='',OrderPriceType='',Direction='',CombOffsetFlag='',CombHedgeFlag='',LimitPrice=0.0,VolumeTotalOriginal=0,TimeCondition='',GTDDate='',VolumeCondition='',MinVolume=0,ContingentCondition='',StopPrice=0.0,ForceCloseReason='',IsAutoSuspend=0,BusinessUnit='',RequestID=0,OrderLocalID='',ExchangeID='',ParticipantID='',ClientID='',ExchangeInstID='',TraderID='',InstallID=0,OrderSubmitStatus='',NotifySequence=0,TradingDay='',SettlementID=0,OrderSysID='',OrderSource='',OrderStatus='',OrderType='',VolumeTraded=0,VolumeTotal=0,InsertDate='',InsertTime='',ActiveTime='',SuspendTime='',UpdateTime='',CancelTime='',ActiveTraderID='',ClearingPartID='',SequenceNo=0,FrontID=0,SessionID=0,UserProductInfo='',StatusMsg='',UserForceClose=0,ActiveUserID='',BrokerOrderSeq=0,RelativeOrderSysID='',ZCETotalTradedVolume=0,IsSwapOrder=0,BranchID='',InvestUnitID='',AccountID='',CurrencyID='',IPAddress='',MacAddress=''):
super(OrderField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.OrderRef=self._to_bytes(OrderRef)
self.UserID=self._to_bytes(UserID)
self.OrderPriceType=self._to_bytes(OrderPriceType)
self.Direction=self._to_bytes(Direction)
self.CombOffsetFlag=self._to_bytes(CombOffsetFlag)
self.CombHedgeFlag=self._to_bytes(CombHedgeFlag)
self.LimitPrice=float(LimitPrice)
self.VolumeTotalOriginal=int(VolumeTotalOriginal)
self.TimeCondition=self._to_bytes(TimeCondition)
self.GTDDate=self._to_bytes(GTDDate)
self.VolumeCondition=self._to_bytes(VolumeCondition)
self.MinVolume=int(MinVolume)
self.ContingentCondition=self._to_bytes(ContingentCondition)
self.StopPrice=float(StopPrice)
self.ForceCloseReason=self._to_bytes(ForceCloseReason)
self.IsAutoSuspend=int(IsAutoSuspend)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.RequestID=int(RequestID)
self.OrderLocalID=self._to_bytes(OrderLocalID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.OrderSubmitStatus=self._to_bytes(OrderSubmitStatus)
self.NotifySequence=int(NotifySequence)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.OrderSysID=self._to_bytes(OrderSysID)
self.OrderSource=self._to_bytes(OrderSource)
self.OrderStatus=self._to_bytes(OrderStatus)
self.OrderType=self._to_bytes(OrderType)
self.VolumeTraded=int(VolumeTraded)
self.VolumeTotal=int(VolumeTotal)
self.InsertDate=self._to_bytes(InsertDate)
self.InsertTime=self._to_bytes(InsertTime)
self.ActiveTime=self._to_bytes(ActiveTime)
self.SuspendTime=self._to_bytes(SuspendTime)
self.UpdateTime=self._to_bytes(UpdateTime)
self.CancelTime=self._to_bytes(CancelTime)
self.ActiveTraderID=self._to_bytes(ActiveTraderID)
self.ClearingPartID=self._to_bytes(ClearingPartID)
self.SequenceNo=int(SequenceNo)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.UserProductInfo=self._to_bytes(UserProductInfo)
self.StatusMsg=self._to_bytes(StatusMsg)
self.UserForceClose=int(UserForceClose)
self.ActiveUserID=self._to_bytes(ActiveUserID)
self.BrokerOrderSeq=int(BrokerOrderSeq)
self.RelativeOrderSysID=self._to_bytes(RelativeOrderSysID)
self.ZCETotalTradedVolume=int(ZCETotalTradedVolume)
self.IsSwapOrder=int(IsSwapOrder)
self.BranchID=self._to_bytes(BranchID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.OrderRef=self._to_bytes(i_tuple[4])
self.UserID=self._to_bytes(i_tuple[5])
self.OrderPriceType=self._to_bytes(i_tuple[6])
self.Direction=self._to_bytes(i_tuple[7])
self.CombOffsetFlag=self._to_bytes(i_tuple[8])
self.CombHedgeFlag=self._to_bytes(i_tuple[9])
self.LimitPrice=float(i_tuple[10])
self.VolumeTotalOriginal=int(i_tuple[11])
self.TimeCondition=self._to_bytes(i_tuple[12])
self.GTDDate=self._to_bytes(i_tuple[13])
self.VolumeCondition=self._to_bytes(i_tuple[14])
self.MinVolume=int(i_tuple[15])
self.ContingentCondition=self._to_bytes(i_tuple[16])
self.StopPrice=float(i_tuple[17])
self.ForceCloseReason=self._to_bytes(i_tuple[18])
self.IsAutoSuspend=int(i_tuple[19])
self.BusinessUnit=self._to_bytes(i_tuple[20])
self.RequestID=int(i_tuple[21])
self.OrderLocalID=self._to_bytes(i_tuple[22])
self.ExchangeID=self._to_bytes(i_tuple[23])
self.ParticipantID=self._to_bytes(i_tuple[24])
self.ClientID=self._to_bytes(i_tuple[25])
self.ExchangeInstID=self._to_bytes(i_tuple[26])
self.TraderID=self._to_bytes(i_tuple[27])
self.InstallID=int(i_tuple[28])
self.OrderSubmitStatus=self._to_bytes(i_tuple[29])
self.NotifySequence=int(i_tuple[30])
self.TradingDay=self._to_bytes(i_tuple[31])
self.SettlementID=int(i_tuple[32])
self.OrderSysID=self._to_bytes(i_tuple[33])
self.OrderSource=self._to_bytes(i_tuple[34])
self.OrderStatus=self._to_bytes(i_tuple[35])
self.OrderType=self._to_bytes(i_tuple[36])
self.VolumeTraded=int(i_tuple[37])
self.VolumeTotal=int(i_tuple[38])
self.InsertDate=self._to_bytes(i_tuple[39])
self.InsertTime=self._to_bytes(i_tuple[40])
self.ActiveTime=self._to_bytes(i_tuple[41])
self.SuspendTime=self._to_bytes(i_tuple[42])
self.UpdateTime=self._to_bytes(i_tuple[43])
self.CancelTime=self._to_bytes(i_tuple[44])
self.ActiveTraderID=self._to_bytes(i_tuple[45])
self.ClearingPartID=self._to_bytes(i_tuple[46])
self.SequenceNo=int(i_tuple[47])
self.FrontID=int(i_tuple[48])
self.SessionID=int(i_tuple[49])
self.UserProductInfo=self._to_bytes(i_tuple[50])
self.StatusMsg=self._to_bytes(i_tuple[51])
self.UserForceClose=int(i_tuple[52])
self.ActiveUserID=self._to_bytes(i_tuple[53])
self.BrokerOrderSeq=int(i_tuple[54])
self.RelativeOrderSysID=self._to_bytes(i_tuple[55])
self.ZCETotalTradedVolume=int(i_tuple[56])
self.IsSwapOrder=int(i_tuple[57])
self.BranchID=self._to_bytes(i_tuple[58])
self.InvestUnitID=self._to_bytes(i_tuple[59])
self.AccountID=self._to_bytes(i_tuple[60])
self.CurrencyID=self._to_bytes(i_tuple[61])
self.IPAddress=self._to_bytes(i_tuple[62])
self.MacAddress=self._to_bytes(i_tuple[63])
class ExchangeOrderField(Base):
"""交易所报单"""
_fields_ = [
('OrderPriceType',ctypes.c_char)# ///报单价格条件
,('Direction',ctypes.c_char)# 买卖方向
,('CombOffsetFlag',ctypes.c_char*5)# 组合开平标志
,('CombHedgeFlag',ctypes.c_char*5)# 组合投机套保标志
,('LimitPrice',ctypes.c_double)# 价格
,('VolumeTotalOriginal',ctypes.c_int)# 数量
,('TimeCondition',ctypes.c_char)# 有效期类型
,('GTDDate',ctypes.c_char*9)# GTD日期
,('VolumeCondition',ctypes.c_char)# 成交量类型
,('MinVolume',ctypes.c_int)# 最小成交量
,('ContingentCondition',ctypes.c_char)# 触发条件
,('StopPrice',ctypes.c_double)# 止损价
,('ForceCloseReason',ctypes.c_char)# 强平原因
,('IsAutoSuspend',ctypes.c_int)# 自动挂起标志
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('RequestID',ctypes.c_int)# 请求编号
,('OrderLocalID',ctypes.c_char*13)# 本地报单编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('OrderSubmitStatus',ctypes.c_char)# 报单提交状态
,('NotifySequence',ctypes.c_int)# 报单提示序号
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('OrderSysID',ctypes.c_char*21)# 报单编号
,('OrderSource',ctypes.c_char)# 报单来源
,('OrderStatus',ctypes.c_char)# 报单状态
,('OrderType',ctypes.c_char)# 报单类型
,('VolumeTraded',ctypes.c_int)# 今成交数量
,('VolumeTotal',ctypes.c_int)# 剩余数量
,('InsertDate',ctypes.c_char*9)# 报单日期
,('InsertTime',ctypes.c_char*9)# 委托时间
,('ActiveTime',ctypes.c_char*9)# 激活时间
,('SuspendTime',ctypes.c_char*9)# 挂起时间
,('UpdateTime',ctypes.c_char*9)# 最后修改时间
,('CancelTime',ctypes.c_char*9)# 撤销时间
,('ActiveTraderID',ctypes.c_char*21)# 最后修改交易所交易员代码
,('ClearingPartID',ctypes.c_char*11)# 结算会员编号
,('SequenceNo',ctypes.c_int)# 序号
,('BranchID',ctypes.c_char*9)# 营业部编号
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,OrderPriceType= '',Direction='',CombOffsetFlag='',CombHedgeFlag='',LimitPrice=0.0,VolumeTotalOriginal=0,TimeCondition='',GTDDate='',VolumeCondition='',MinVolume=0,ContingentCondition='',StopPrice=0.0,ForceCloseReason='',IsAutoSuspend=0,BusinessUnit='',RequestID=0,OrderLocalID='',ExchangeID='',ParticipantID='',ClientID='',ExchangeInstID='',TraderID='',InstallID=0,OrderSubmitStatus='',NotifySequence=0,TradingDay='',SettlementID=0,OrderSysID='',OrderSource='',OrderStatus='',OrderType='',VolumeTraded=0,VolumeTotal=0,InsertDate='',InsertTime='',ActiveTime='',SuspendTime='',UpdateTime='',CancelTime='',ActiveTraderID='',ClearingPartID='',SequenceNo=0,BranchID='',IPAddress='',MacAddress=''):
super(ExchangeOrderField,self).__init__()
self.OrderPriceType=self._to_bytes(OrderPriceType)
self.Direction=self._to_bytes(Direction)
self.CombOffsetFlag=self._to_bytes(CombOffsetFlag)
self.CombHedgeFlag=self._to_bytes(CombHedgeFlag)
self.LimitPrice=float(LimitPrice)
self.VolumeTotalOriginal=int(VolumeTotalOriginal)
self.TimeCondition=self._to_bytes(TimeCondition)
self.GTDDate=self._to_bytes(GTDDate)
self.VolumeCondition=self._to_bytes(VolumeCondition)
self.MinVolume=int(MinVolume)
self.ContingentCondition=self._to_bytes(ContingentCondition)
self.StopPrice=float(StopPrice)
self.ForceCloseReason=self._to_bytes(ForceCloseReason)
self.IsAutoSuspend=int(IsAutoSuspend)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.RequestID=int(RequestID)
self.OrderLocalID=self._to_bytes(OrderLocalID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.OrderSubmitStatus=self._to_bytes(OrderSubmitStatus)
self.NotifySequence=int(NotifySequence)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.OrderSysID=self._to_bytes(OrderSysID)
self.OrderSource=self._to_bytes(OrderSource)
self.OrderStatus=self._to_bytes(OrderStatus)
self.OrderType=self._to_bytes(OrderType)
self.VolumeTraded=int(VolumeTraded)
self.VolumeTotal=int(VolumeTotal)
self.InsertDate=self._to_bytes(InsertDate)
self.InsertTime=self._to_bytes(InsertTime)
self.ActiveTime=self._to_bytes(ActiveTime)
self.SuspendTime=self._to_bytes(SuspendTime)
self.UpdateTime=self._to_bytes(UpdateTime)
self.CancelTime=self._to_bytes(CancelTime)
self.ActiveTraderID=self._to_bytes(ActiveTraderID)
self.ClearingPartID=self._to_bytes(ClearingPartID)
self.SequenceNo=int(SequenceNo)
self.BranchID=self._to_bytes(BranchID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.OrderPriceType=self._to_bytes(i_tuple[1])
self.Direction=self._to_bytes(i_tuple[2])
self.CombOffsetFlag=self._to_bytes(i_tuple[3])
self.CombHedgeFlag=self._to_bytes(i_tuple[4])
self.LimitPrice=float(i_tuple[5])
self.VolumeTotalOriginal=int(i_tuple[6])
self.TimeCondition=self._to_bytes(i_tuple[7])
self.GTDDate=self._to_bytes(i_tuple[8])
self.VolumeCondition=self._to_bytes(i_tuple[9])
self.MinVolume=int(i_tuple[10])
self.ContingentCondition=self._to_bytes(i_tuple[11])
self.StopPrice=float(i_tuple[12])
self.ForceCloseReason=self._to_bytes(i_tuple[13])
self.IsAutoSuspend=int(i_tuple[14])
self.BusinessUnit=self._to_bytes(i_tuple[15])
self.RequestID=int(i_tuple[16])
self.OrderLocalID=self._to_bytes(i_tuple[17])
self.ExchangeID=self._to_bytes(i_tuple[18])
self.ParticipantID=self._to_bytes(i_tuple[19])
self.ClientID=self._to_bytes(i_tuple[20])
self.ExchangeInstID=self._to_bytes(i_tuple[21])
self.TraderID=self._to_bytes(i_tuple[22])
self.InstallID=int(i_tuple[23])
self.OrderSubmitStatus=self._to_bytes(i_tuple[24])
self.NotifySequence=int(i_tuple[25])
self.TradingDay=self._to_bytes(i_tuple[26])
self.SettlementID=int(i_tuple[27])
self.OrderSysID=self._to_bytes(i_tuple[28])
self.OrderSource=self._to_bytes(i_tuple[29])
self.OrderStatus=self._to_bytes(i_tuple[30])
self.OrderType=self._to_bytes(i_tuple[31])
self.VolumeTraded=int(i_tuple[32])
self.VolumeTotal=int(i_tuple[33])
self.InsertDate=self._to_bytes(i_tuple[34])
self.InsertTime=self._to_bytes(i_tuple[35])
self.ActiveTime=self._to_bytes(i_tuple[36])
self.SuspendTime=self._to_bytes(i_tuple[37])
self.UpdateTime=self._to_bytes(i_tuple[38])
self.CancelTime=self._to_bytes(i_tuple[39])
self.ActiveTraderID=self._to_bytes(i_tuple[40])
self.ClearingPartID=self._to_bytes(i_tuple[41])
self.SequenceNo=int(i_tuple[42])
self.BranchID=self._to_bytes(i_tuple[43])
self.IPAddress=self._to_bytes(i_tuple[44])
self.MacAddress=self._to_bytes(i_tuple[45])
class ExchangeOrderInsertErrorField(Base):
"""交易所报单插入失败"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('OrderLocalID',ctypes.c_char*13)# 本地报单编号
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
]
def __init__(self,ExchangeID= '',ParticipantID='',TraderID='',InstallID=0,OrderLocalID='',ErrorID=0,ErrorMsg=''):
super(ExchangeOrderInsertErrorField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.OrderLocalID=self._to_bytes(OrderLocalID)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.ParticipantID=self._to_bytes(i_tuple[2])
self.TraderID=self._to_bytes(i_tuple[3])
self.InstallID=int(i_tuple[4])
self.OrderLocalID=self._to_bytes(i_tuple[5])
self.ErrorID=int(i_tuple[6])
self.ErrorMsg=self._to_bytes(i_tuple[7])
class InputOrderActionField(Base):
"""输入报单操作"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('OrderActionRef',ctypes.c_int)# 报单操作引用
,('OrderRef',ctypes.c_char*13)# 报单引用
,('RequestID',ctypes.c_int)# 请求编号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('OrderSysID',ctypes.c_char*21)# 报单编号
,('ActionFlag',ctypes.c_char)# 操作标志
,('LimitPrice',ctypes.c_double)# 价格
,('VolumeChange',ctypes.c_int)# 数量变化
,('UserID',ctypes.c_char*16)# 用户代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',OrderActionRef=0,OrderRef='',RequestID=0,FrontID=0,SessionID=0,ExchangeID='',OrderSysID='',ActionFlag='',LimitPrice=0.0,VolumeChange=0,UserID='',InstrumentID='',InvestUnitID='',IPAddress='',MacAddress=''):
super(InputOrderActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.OrderActionRef=int(OrderActionRef)
self.OrderRef=self._to_bytes(OrderRef)
self.RequestID=int(RequestID)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.OrderSysID=self._to_bytes(OrderSysID)
self.ActionFlag=self._to_bytes(ActionFlag)
self.LimitPrice=float(LimitPrice)
self.VolumeChange=int(VolumeChange)
self.UserID=self._to_bytes(UserID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.OrderActionRef=int(i_tuple[3])
self.OrderRef=self._to_bytes(i_tuple[4])
self.RequestID=int(i_tuple[5])
self.FrontID=int(i_tuple[6])
self.SessionID=int(i_tuple[7])
self.ExchangeID=self._to_bytes(i_tuple[8])
self.OrderSysID=self._to_bytes(i_tuple[9])
self.ActionFlag=self._to_bytes(i_tuple[10])
self.LimitPrice=float(i_tuple[11])
self.VolumeChange=int(i_tuple[12])
self.UserID=self._to_bytes(i_tuple[13])
self.InstrumentID=self._to_bytes(i_tuple[14])
self.InvestUnitID=self._to_bytes(i_tuple[15])
self.IPAddress=self._to_bytes(i_tuple[16])
self.MacAddress=self._to_bytes(i_tuple[17])
class OrderActionField(Base):
"""报单操作"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('OrderActionRef',ctypes.c_int)# 报单操作引用
,('OrderRef',ctypes.c_char*13)# 报单引用
,('RequestID',ctypes.c_int)# 请求编号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('OrderSysID',ctypes.c_char*21)# 报单编号
,('ActionFlag',ctypes.c_char)# 操作标志
,('LimitPrice',ctypes.c_double)# 价格
,('VolumeChange',ctypes.c_int)# 数量变化
,('ActionDate',ctypes.c_char*9)# 操作日期
,('ActionTime',ctypes.c_char*9)# 操作时间
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('OrderLocalID',ctypes.c_char*13)# 本地报单编号
,('ActionLocalID',ctypes.c_char*13)# 操作本地编号
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('OrderActionStatus',ctypes.c_char)# 报单操作状态
,('UserID',ctypes.c_char*16)# 用户代码
,('StatusMsg',ctypes.c_char*81)# 状态信息
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('BranchID',ctypes.c_char*9)# 营业部编号
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',OrderActionRef=0,OrderRef='',RequestID=0,FrontID=0,SessionID=0,ExchangeID='',OrderSysID='',ActionFlag='',LimitPrice=0.0,VolumeChange=0,ActionDate='',ActionTime='',TraderID='',InstallID=0,OrderLocalID='',ActionLocalID='',ParticipantID='',ClientID='',BusinessUnit='',OrderActionStatus='',UserID='',StatusMsg='',InstrumentID='',BranchID='',InvestUnitID='',IPAddress='',MacAddress=''):
super(OrderActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.OrderActionRef=int(OrderActionRef)
self.OrderRef=self._to_bytes(OrderRef)
self.RequestID=int(RequestID)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.OrderSysID=self._to_bytes(OrderSysID)
self.ActionFlag=self._to_bytes(ActionFlag)
self.LimitPrice=float(LimitPrice)
self.VolumeChange=int(VolumeChange)
self.ActionDate=self._to_bytes(ActionDate)
self.ActionTime=self._to_bytes(ActionTime)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.OrderLocalID=self._to_bytes(OrderLocalID)
self.ActionLocalID=self._to_bytes(ActionLocalID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.OrderActionStatus=self._to_bytes(OrderActionStatus)
self.UserID=self._to_bytes(UserID)
self.StatusMsg=self._to_bytes(StatusMsg)
self.InstrumentID=self._to_bytes(InstrumentID)
self.BranchID=self._to_bytes(BranchID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.OrderActionRef=int(i_tuple[3])
self.OrderRef=self._to_bytes(i_tuple[4])
self.RequestID=int(i_tuple[5])
self.FrontID=int(i_tuple[6])
self.SessionID=int(i_tuple[7])
self.ExchangeID=self._to_bytes(i_tuple[8])
self.OrderSysID=self._to_bytes(i_tuple[9])
self.ActionFlag=self._to_bytes(i_tuple[10])
self.LimitPrice=float(i_tuple[11])
self.VolumeChange=int(i_tuple[12])
self.ActionDate=self._to_bytes(i_tuple[13])
self.ActionTime=self._to_bytes(i_tuple[14])
self.TraderID=self._to_bytes(i_tuple[15])
self.InstallID=int(i_tuple[16])
self.OrderLocalID=self._to_bytes(i_tuple[17])
self.ActionLocalID=self._to_bytes(i_tuple[18])
self.ParticipantID=self._to_bytes(i_tuple[19])
self.ClientID=self._to_bytes(i_tuple[20])
self.BusinessUnit=self._to_bytes(i_tuple[21])
self.OrderActionStatus=self._to_bytes(i_tuple[22])
self.UserID=self._to_bytes(i_tuple[23])
self.StatusMsg=self._to_bytes(i_tuple[24])
self.InstrumentID=self._to_bytes(i_tuple[25])
self.BranchID=self._to_bytes(i_tuple[26])
self.InvestUnitID=self._to_bytes(i_tuple[27])
self.IPAddress=self._to_bytes(i_tuple[28])
self.MacAddress=self._to_bytes(i_tuple[29])
class ExchangeOrderActionField(Base):
"""交易所报单操作"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('OrderSysID',ctypes.c_char*21)# 报单编号
,('ActionFlag',ctypes.c_char)# 操作标志
,('LimitPrice',ctypes.c_double)# 价格
,('VolumeChange',ctypes.c_int)# 数量变化
,('ActionDate',ctypes.c_char*9)# 操作日期
,('ActionTime',ctypes.c_char*9)# 操作时间
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('OrderLocalID',ctypes.c_char*13)# 本地报单编号
,('ActionLocalID',ctypes.c_char*13)# 操作本地编号
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('OrderActionStatus',ctypes.c_char)# 报单操作状态
,('UserID',ctypes.c_char*16)# 用户代码
,('BranchID',ctypes.c_char*9)# 营业部编号
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,ExchangeID= '',OrderSysID='',ActionFlag='',LimitPrice=0.0,VolumeChange=0,ActionDate='',ActionTime='',TraderID='',InstallID=0,OrderLocalID='',ActionLocalID='',ParticipantID='',ClientID='',BusinessUnit='',OrderActionStatus='',UserID='',BranchID='',IPAddress='',MacAddress=''):
super(ExchangeOrderActionField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.OrderSysID=self._to_bytes(OrderSysID)
self.ActionFlag=self._to_bytes(ActionFlag)
self.LimitPrice=float(LimitPrice)
self.VolumeChange=int(VolumeChange)
self.ActionDate=self._to_bytes(ActionDate)
self.ActionTime=self._to_bytes(ActionTime)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.OrderLocalID=self._to_bytes(OrderLocalID)
self.ActionLocalID=self._to_bytes(ActionLocalID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.OrderActionStatus=self._to_bytes(OrderActionStatus)
self.UserID=self._to_bytes(UserID)
self.BranchID=self._to_bytes(BranchID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.OrderSysID=self._to_bytes(i_tuple[2])
self.ActionFlag=self._to_bytes(i_tuple[3])
self.LimitPrice=float(i_tuple[4])
self.VolumeChange=int(i_tuple[5])
self.ActionDate=self._to_bytes(i_tuple[6])
self.ActionTime=self._to_bytes(i_tuple[7])
self.TraderID=self._to_bytes(i_tuple[8])
self.InstallID=int(i_tuple[9])
self.OrderLocalID=self._to_bytes(i_tuple[10])
self.ActionLocalID=self._to_bytes(i_tuple[11])
self.ParticipantID=self._to_bytes(i_tuple[12])
self.ClientID=self._to_bytes(i_tuple[13])
self.BusinessUnit=self._to_bytes(i_tuple[14])
self.OrderActionStatus=self._to_bytes(i_tuple[15])
self.UserID=self._to_bytes(i_tuple[16])
self.BranchID=self._to_bytes(i_tuple[17])
self.IPAddress=self._to_bytes(i_tuple[18])
self.MacAddress=self._to_bytes(i_tuple[19])
class ExchangeOrderActionErrorField(Base):
"""交易所报单操作失败"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('OrderSysID',ctypes.c_char*21)# 报单编号
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('OrderLocalID',ctypes.c_char*13)# 本地报单编号
,('ActionLocalID',ctypes.c_char*13)# 操作本地编号
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
]
def __init__(self,ExchangeID= '',OrderSysID='',TraderID='',InstallID=0,OrderLocalID='',ActionLocalID='',ErrorID=0,ErrorMsg=''):
super(ExchangeOrderActionErrorField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.OrderSysID=self._to_bytes(OrderSysID)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.OrderLocalID=self._to_bytes(OrderLocalID)
self.ActionLocalID=self._to_bytes(ActionLocalID)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.OrderSysID=self._to_bytes(i_tuple[2])
self.TraderID=self._to_bytes(i_tuple[3])
self.InstallID=int(i_tuple[4])
self.OrderLocalID=self._to_bytes(i_tuple[5])
self.ActionLocalID=self._to_bytes(i_tuple[6])
self.ErrorID=int(i_tuple[7])
self.ErrorMsg=self._to_bytes(i_tuple[8])
class ExchangeTradeField(Base):
"""交易所成交"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('TradeID',ctypes.c_char*21)# 成交编号
,('Direction',ctypes.c_char)# 买卖方向
,('OrderSysID',ctypes.c_char*21)# 报单编号
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('TradingRole',ctypes.c_char)# 交易角色
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('OffsetFlag',ctypes.c_char)# 开平标志
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('Price',ctypes.c_double)# 价格
,('Volume',ctypes.c_int)# 数量
,('TradeDate',ctypes.c_char*9)# 成交时期
,('TradeTime',ctypes.c_char*9)# 成交时间
,('TradeType',ctypes.c_char)# 成交类型
,('PriceSource',ctypes.c_char)# 成交价来源
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('OrderLocalID',ctypes.c_char*13)# 本地报单编号
,('ClearingPartID',ctypes.c_char*11)# 结算会员编号
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('SequenceNo',ctypes.c_int)# 序号
,('TradeSource',ctypes.c_char)# 成交来源
]
def __init__(self,ExchangeID= '',TradeID='',Direction='',OrderSysID='',ParticipantID='',ClientID='',TradingRole='',ExchangeInstID='',OffsetFlag='',HedgeFlag='',Price=0.0,Volume=0,TradeDate='',TradeTime='',TradeType='',PriceSource='',TraderID='',OrderLocalID='',ClearingPartID='',BusinessUnit='',SequenceNo=0,TradeSource=''):
super(ExchangeTradeField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.TradeID=self._to_bytes(TradeID)
self.Direction=self._to_bytes(Direction)
self.OrderSysID=self._to_bytes(OrderSysID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.TradingRole=self._to_bytes(TradingRole)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.OffsetFlag=self._to_bytes(OffsetFlag)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.Price=float(Price)
self.Volume=int(Volume)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.TradeType=self._to_bytes(TradeType)
self.PriceSource=self._to_bytes(PriceSource)
self.TraderID=self._to_bytes(TraderID)
self.OrderLocalID=self._to_bytes(OrderLocalID)
self.ClearingPartID=self._to_bytes(ClearingPartID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.SequenceNo=int(SequenceNo)
self.TradeSource=self._to_bytes(TradeSource)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.TradeID=self._to_bytes(i_tuple[2])
self.Direction=self._to_bytes(i_tuple[3])
self.OrderSysID=self._to_bytes(i_tuple[4])
self.ParticipantID=self._to_bytes(i_tuple[5])
self.ClientID=self._to_bytes(i_tuple[6])
self.TradingRole=self._to_bytes(i_tuple[7])
self.ExchangeInstID=self._to_bytes(i_tuple[8])
self.OffsetFlag=self._to_bytes(i_tuple[9])
self.HedgeFlag=self._to_bytes(i_tuple[10])
self.Price=float(i_tuple[11])
self.Volume=int(i_tuple[12])
self.TradeDate=self._to_bytes(i_tuple[13])
self.TradeTime=self._to_bytes(i_tuple[14])
self.TradeType=self._to_bytes(i_tuple[15])
self.PriceSource=self._to_bytes(i_tuple[16])
self.TraderID=self._to_bytes(i_tuple[17])
self.OrderLocalID=self._to_bytes(i_tuple[18])
self.ClearingPartID=self._to_bytes(i_tuple[19])
self.BusinessUnit=self._to_bytes(i_tuple[20])
self.SequenceNo=int(i_tuple[21])
self.TradeSource=self._to_bytes(i_tuple[22])
class TradeField(Base):
"""成交"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('OrderRef',ctypes.c_char*13)# 报单引用
,('UserID',ctypes.c_char*16)# 用户代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('TradeID',ctypes.c_char*21)# 成交编号
,('Direction',ctypes.c_char)# 买卖方向
,('OrderSysID',ctypes.c_char*21)# 报单编号
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('TradingRole',ctypes.c_char)# 交易角色
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('OffsetFlag',ctypes.c_char)# 开平标志
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('Price',ctypes.c_double)# 价格
,('Volume',ctypes.c_int)# 数量
,('TradeDate',ctypes.c_char*9)# 成交时期
,('TradeTime',ctypes.c_char*9)# 成交时间
,('TradeType',ctypes.c_char)# 成交类型
,('PriceSource',ctypes.c_char)# 成交价来源
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('OrderLocalID',ctypes.c_char*13)# 本地报单编号
,('ClearingPartID',ctypes.c_char*11)# 结算会员编号
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('SequenceNo',ctypes.c_int)# 序号
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('BrokerOrderSeq',ctypes.c_int)# 经纪公司报单编号
,('TradeSource',ctypes.c_char)# 成交来源
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',OrderRef='',UserID='',ExchangeID='',TradeID='',Direction='',OrderSysID='',ParticipantID='',ClientID='',TradingRole='',ExchangeInstID='',OffsetFlag='',HedgeFlag='',Price=0.0,Volume=0,TradeDate='',TradeTime='',TradeType='',PriceSource='',TraderID='',OrderLocalID='',ClearingPartID='',BusinessUnit='',SequenceNo=0,TradingDay='',SettlementID=0,BrokerOrderSeq=0,TradeSource='',InvestUnitID=''):
super(TradeField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.OrderRef=self._to_bytes(OrderRef)
self.UserID=self._to_bytes(UserID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.TradeID=self._to_bytes(TradeID)
self.Direction=self._to_bytes(Direction)
self.OrderSysID=self._to_bytes(OrderSysID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.TradingRole=self._to_bytes(TradingRole)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.OffsetFlag=self._to_bytes(OffsetFlag)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.Price=float(Price)
self.Volume=int(Volume)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.TradeType=self._to_bytes(TradeType)
self.PriceSource=self._to_bytes(PriceSource)
self.TraderID=self._to_bytes(TraderID)
self.OrderLocalID=self._to_bytes(OrderLocalID)
self.ClearingPartID=self._to_bytes(ClearingPartID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.SequenceNo=int(SequenceNo)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.BrokerOrderSeq=int(BrokerOrderSeq)
self.TradeSource=self._to_bytes(TradeSource)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.OrderRef=self._to_bytes(i_tuple[4])
self.UserID=self._to_bytes(i_tuple[5])
self.ExchangeID=self._to_bytes(i_tuple[6])
self.TradeID=self._to_bytes(i_tuple[7])
self.Direction=self._to_bytes(i_tuple[8])
self.OrderSysID=self._to_bytes(i_tuple[9])
self.ParticipantID=self._to_bytes(i_tuple[10])
self.ClientID=self._to_bytes(i_tuple[11])
self.TradingRole=self._to_bytes(i_tuple[12])
self.ExchangeInstID=self._to_bytes(i_tuple[13])
self.OffsetFlag=self._to_bytes(i_tuple[14])
self.HedgeFlag=self._to_bytes(i_tuple[15])
self.Price=float(i_tuple[16])
self.Volume=int(i_tuple[17])
self.TradeDate=self._to_bytes(i_tuple[18])
self.TradeTime=self._to_bytes(i_tuple[19])
self.TradeType=self._to_bytes(i_tuple[20])
self.PriceSource=self._to_bytes(i_tuple[21])
self.TraderID=self._to_bytes(i_tuple[22])
self.OrderLocalID=self._to_bytes(i_tuple[23])
self.ClearingPartID=self._to_bytes(i_tuple[24])
self.BusinessUnit=self._to_bytes(i_tuple[25])
self.SequenceNo=int(i_tuple[26])
self.TradingDay=self._to_bytes(i_tuple[27])
self.SettlementID=int(i_tuple[28])
self.BrokerOrderSeq=int(i_tuple[29])
self.TradeSource=self._to_bytes(i_tuple[30])
self.InvestUnitID=self._to_bytes(i_tuple[31])
class UserSessionField(Base):
"""用户会话"""
_fields_ = [
('FrontID',ctypes.c_int)# ///前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('LoginDate',ctypes.c_char*9)# 登录日期
,('LoginTime',ctypes.c_char*9)# 登录时间
,('IPAddress',ctypes.c_char*16)# IP地址
,('UserProductInfo',ctypes.c_char*11)# 用户端产品信息
,('InterfaceProductInfo',ctypes.c_char*11)# 接口端产品信息
,('ProtocolInfo',ctypes.c_char*11)# 协议信息
,('MacAddress',ctypes.c_char*21)# Mac地址
,('LoginRemark',ctypes.c_char*36)# 登录备注
]
def __init__(self,FrontID= 0,SessionID=0,BrokerID='',UserID='',LoginDate='',LoginTime='',IPAddress='',UserProductInfo='',InterfaceProductInfo='',ProtocolInfo='',MacAddress='',LoginRemark=''):
super(UserSessionField,self).__init__()
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.LoginDate=self._to_bytes(LoginDate)
self.LoginTime=self._to_bytes(LoginTime)
self.IPAddress=self._to_bytes(IPAddress)
self.UserProductInfo=self._to_bytes(UserProductInfo)
self.InterfaceProductInfo=self._to_bytes(InterfaceProductInfo)
self.ProtocolInfo=self._to_bytes(ProtocolInfo)
self.MacAddress=self._to_bytes(MacAddress)
self.LoginRemark=self._to_bytes(LoginRemark)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.FrontID=int(i_tuple[1])
self.SessionID=int(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.UserID=self._to_bytes(i_tuple[4])
self.LoginDate=self._to_bytes(i_tuple[5])
self.LoginTime=self._to_bytes(i_tuple[6])
self.IPAddress=self._to_bytes(i_tuple[7])
self.UserProductInfo=self._to_bytes(i_tuple[8])
self.InterfaceProductInfo=self._to_bytes(i_tuple[9])
self.ProtocolInfo=self._to_bytes(i_tuple[10])
self.MacAddress=self._to_bytes(i_tuple[11])
self.LoginRemark=self._to_bytes(i_tuple[12])
class QueryMaxOrderVolumeField(Base):
"""查询最大报单数量"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('Direction',ctypes.c_char)# 买卖方向
,('OffsetFlag',ctypes.c_char)# 开平标志
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('MaxVolume',ctypes.c_int)# 最大允许报单数量
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',Direction='',OffsetFlag='',HedgeFlag='',MaxVolume=0,ExchangeID='',InvestUnitID=''):
super(QueryMaxOrderVolumeField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.Direction=self._to_bytes(Direction)
self.OffsetFlag=self._to_bytes(OffsetFlag)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.MaxVolume=int(MaxVolume)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.Direction=self._to_bytes(i_tuple[4])
self.OffsetFlag=self._to_bytes(i_tuple[5])
self.HedgeFlag=self._to_bytes(i_tuple[6])
self.MaxVolume=int(i_tuple[7])
self.ExchangeID=self._to_bytes(i_tuple[8])
self.InvestUnitID=self._to_bytes(i_tuple[9])
class SettlementInfoConfirmField(Base):
"""投资者结算结果确认信息"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('ConfirmDate',ctypes.c_char*9)# 确认日期
,('ConfirmTime',ctypes.c_char*9)# 确认时间
,('SettlementID',ctypes.c_int)# 结算编号
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('CurrencyID',ctypes.c_char*4)# 币种代码
]
def __init__(self,BrokerID= '',InvestorID='',ConfirmDate='',ConfirmTime='',SettlementID=0,AccountID='',CurrencyID=''):
super(SettlementInfoConfirmField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.ConfirmDate=self._to_bytes(ConfirmDate)
self.ConfirmTime=self._to_bytes(ConfirmTime)
self.SettlementID=int(SettlementID)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.ConfirmDate=self._to_bytes(i_tuple[3])
self.ConfirmTime=self._to_bytes(i_tuple[4])
self.SettlementID=int(i_tuple[5])
self.AccountID=self._to_bytes(i_tuple[6])
self.CurrencyID=self._to_bytes(i_tuple[7])
class SyncDepositField(Base):
"""出入金同步"""
_fields_ = [
('DepositSeqNo',ctypes.c_char*15)# ///出入金流水号
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('Deposit',ctypes.c_double)# 入金金额
,('IsForce',ctypes.c_int)# 是否强制进行
,('CurrencyID',ctypes.c_char*4)# 币种代码
]
def __init__(self,DepositSeqNo= '',BrokerID='',InvestorID='',Deposit=0.0,IsForce=0,CurrencyID=''):
super(SyncDepositField,self).__init__()
self.DepositSeqNo=self._to_bytes(DepositSeqNo)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.Deposit=float(Deposit)
self.IsForce=int(IsForce)
self.CurrencyID=self._to_bytes(CurrencyID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.DepositSeqNo=self._to_bytes(i_tuple[1])
self.BrokerID=self._to_bytes(i_tuple[2])
self.InvestorID=self._to_bytes(i_tuple[3])
self.Deposit=float(i_tuple[4])
self.IsForce=int(i_tuple[5])
self.CurrencyID=self._to_bytes(i_tuple[6])
class SyncFundMortgageField(Base):
"""货币质押同步"""
_fields_ = [
('MortgageSeqNo',ctypes.c_char*15)# ///货币质押流水号
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('FromCurrencyID',ctypes.c_char*4)# 源币种
,('MortgageAmount',ctypes.c_double)# 质押金额
,('ToCurrencyID',ctypes.c_char*4)# 目标币种
]
def __init__(self,MortgageSeqNo= '',BrokerID='',InvestorID='',FromCurrencyID='',MortgageAmount=0.0,ToCurrencyID=''):
super(SyncFundMortgageField,self).__init__()
self.MortgageSeqNo=self._to_bytes(MortgageSeqNo)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.FromCurrencyID=self._to_bytes(FromCurrencyID)
self.MortgageAmount=float(MortgageAmount)
self.ToCurrencyID=self._to_bytes(ToCurrencyID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.MortgageSeqNo=self._to_bytes(i_tuple[1])
self.BrokerID=self._to_bytes(i_tuple[2])
self.InvestorID=self._to_bytes(i_tuple[3])
self.FromCurrencyID=self._to_bytes(i_tuple[4])
self.MortgageAmount=float(i_tuple[5])
self.ToCurrencyID=self._to_bytes(i_tuple[6])
class BrokerSyncField(Base):
"""经纪公司同步"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
]
def __init__(self,BrokerID= ''):
super(BrokerSyncField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
class SyncingInvestorField(Base):
"""正在同步中的投资者"""
_fields_ = [
('InvestorID',ctypes.c_char*13)# ///投资者代码
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorGroupID',ctypes.c_char*13)# 投资者分组代码
,('InvestorName',ctypes.c_char*81)# 投资者名称
,('IdentifiedCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('IsActive',ctypes.c_int)# 是否活跃
,('Telephone',ctypes.c_char*41)# 联系电话
,('Address',ctypes.c_char*101)# 通讯地址
,('OpenDate',ctypes.c_char*9)# 开户日期
,('Mobile',ctypes.c_char*41)# 手机
,('CommModelID',ctypes.c_char*13)# 手续费率模板代码
,('MarginModelID',ctypes.c_char*13)# 保证金率模板代码
]
def __init__(self,InvestorID= '',BrokerID='',InvestorGroupID='',InvestorName='',IdentifiedCardType='',IdentifiedCardNo='',IsActive=0,Telephone='',Address='',OpenDate='',Mobile='',CommModelID='',MarginModelID=''):
super(SyncingInvestorField,self).__init__()
self.InvestorID=self._to_bytes(InvestorID)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorGroupID=self._to_bytes(InvestorGroupID)
self.InvestorName=self._to_bytes(InvestorName)
self.IdentifiedCardType=self._to_bytes(IdentifiedCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.IsActive=int(IsActive)
self.Telephone=self._to_bytes(Telephone)
self.Address=self._to_bytes(Address)
self.OpenDate=self._to_bytes(OpenDate)
self.Mobile=self._to_bytes(Mobile)
self.CommModelID=self._to_bytes(CommModelID)
self.MarginModelID=self._to_bytes(MarginModelID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InvestorID=self._to_bytes(i_tuple[1])
self.BrokerID=self._to_bytes(i_tuple[2])
self.InvestorGroupID=self._to_bytes(i_tuple[3])
self.InvestorName=self._to_bytes(i_tuple[4])
self.IdentifiedCardType=self._to_bytes(i_tuple[5])
self.IdentifiedCardNo=self._to_bytes(i_tuple[6])
self.IsActive=int(i_tuple[7])
self.Telephone=self._to_bytes(i_tuple[8])
self.Address=self._to_bytes(i_tuple[9])
self.OpenDate=self._to_bytes(i_tuple[10])
self.Mobile=self._to_bytes(i_tuple[11])
self.CommModelID=self._to_bytes(i_tuple[12])
self.MarginModelID=self._to_bytes(i_tuple[13])
class SyncingTradingCodeField(Base):
"""正在同步中的交易代码"""
_fields_ = [
('InvestorID',ctypes.c_char*13)# ///投资者代码
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('IsActive',ctypes.c_int)# 是否活跃
,('ClientIDType',ctypes.c_char)# 交易编码类型
]
def __init__(self,InvestorID= '',BrokerID='',ExchangeID='',ClientID='',IsActive=0,ClientIDType=''):
super(SyncingTradingCodeField,self).__init__()
self.InvestorID=self._to_bytes(InvestorID)
self.BrokerID=self._to_bytes(BrokerID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ClientID=self._to_bytes(ClientID)
self.IsActive=int(IsActive)
self.ClientIDType=self._to_bytes(ClientIDType)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InvestorID=self._to_bytes(i_tuple[1])
self.BrokerID=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
self.ClientID=self._to_bytes(i_tuple[4])
self.IsActive=int(i_tuple[5])
self.ClientIDType=self._to_bytes(i_tuple[6])
class SyncingInvestorGroupField(Base):
"""正在同步中的投资者分组"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorGroupID',ctypes.c_char*13)# 投资者分组代码
,('InvestorGroupName',ctypes.c_char*41)# 投资者分组名称
]
def __init__(self,BrokerID= '',InvestorGroupID='',InvestorGroupName=''):
super(SyncingInvestorGroupField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorGroupID=self._to_bytes(InvestorGroupID)
self.InvestorGroupName=self._to_bytes(InvestorGroupName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorGroupID=self._to_bytes(i_tuple[2])
self.InvestorGroupName=self._to_bytes(i_tuple[3])
class SyncingTradingAccountField(Base):
"""正在同步中的交易账号"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('PreMortgage',ctypes.c_double)# 上次质押金额
,('PreCredit',ctypes.c_double)# 上次信用额度
,('PreDeposit',ctypes.c_double)# 上次存款额
,('PreBalance',ctypes.c_double)# 上次结算准备金
,('PreMargin',ctypes.c_double)# 上次占用的保证金
,('InterestBase',ctypes.c_double)# 利息基数
,('Interest',ctypes.c_double)# 利息收入
,('Deposit',ctypes.c_double)# 入金金额
,('Withdraw',ctypes.c_double)# 出金金额
,('FrozenMargin',ctypes.c_double)# 冻结的保证金
,('FrozenCash',ctypes.c_double)# 冻结的资金
,('FrozenCommission',ctypes.c_double)# 冻结的手续费
,('CurrMargin',ctypes.c_double)# 当前保证金总额
,('CashIn',ctypes.c_double)# 资金差额
,('Commission',ctypes.c_double)# 手续费
,('CloseProfit',ctypes.c_double)# 平仓盈亏
,('PositionProfit',ctypes.c_double)# 持仓盈亏
,('Balance',ctypes.c_double)# 期货结算准备金
,('Available',ctypes.c_double)# 可用资金
,('WithdrawQuota',ctypes.c_double)# 可取资金
,('Reserve',ctypes.c_double)# 基本准备金
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('Credit',ctypes.c_double)# 信用额度
,('Mortgage',ctypes.c_double)# 质押金额
,('ExchangeMargin',ctypes.c_double)# 交易所保证金
,('DeliveryMargin',ctypes.c_double)# 投资者交割保证金
,('ExchangeDeliveryMargin',ctypes.c_double)# 交易所交割保证金
,('ReserveBalance',ctypes.c_double)# 保底期货结算准备金
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('PreFundMortgageIn',ctypes.c_double)# 上次货币质入金额
,('PreFundMortgageOut',ctypes.c_double)# 上次货币质出金额
,('FundMortgageIn',ctypes.c_double)# 货币质入金额
,('FundMortgageOut',ctypes.c_double)# 货币质出金额
,('FundMortgageAvailable',ctypes.c_double)# 货币质押余额
,('MortgageableFund',ctypes.c_double)# 可质押货币金额
,('SpecProductMargin',ctypes.c_double)# 特殊产品占用保证金
,('SpecProductFrozenMargin',ctypes.c_double)# 特殊产品冻结保证金
,('SpecProductCommission',ctypes.c_double)# 特殊产品手续费
,('SpecProductFrozenCommission',ctypes.c_double)# 特殊产品冻结手续费
,('SpecProductPositionProfit',ctypes.c_double)# 特殊产品持仓盈亏
,('SpecProductCloseProfit',ctypes.c_double)# 特殊产品平仓盈亏
,('SpecProductPositionProfitByAlg',ctypes.c_double)# 根据持仓盈亏算法计算的特殊产品持仓盈亏
,('SpecProductExchangeMargin',ctypes.c_double)# 特殊产品交易所保证金
,('FrozenSwap',ctypes.c_double)# 延时换汇冻结金额
,('RemainSwap',ctypes.c_double)# 剩余换汇额度
]
def __init__(self,BrokerID= '',AccountID='',PreMortgage=0.0,PreCredit=0.0,PreDeposit=0.0,PreBalance=0.0,PreMargin=0.0,InterestBase=0.0,Interest=0.0,Deposit=0.0,Withdraw=0.0,FrozenMargin=0.0,FrozenCash=0.0,FrozenCommission=0.0,CurrMargin=0.0,CashIn=0.0,Commission=0.0,CloseProfit=0.0,PositionProfit=0.0,Balance=0.0,Available=0.0,WithdrawQuota=0.0,Reserve=0.0,TradingDay='',SettlementID=0,Credit=0.0,Mortgage=0.0,ExchangeMargin=0.0,DeliveryMargin=0.0,ExchangeDeliveryMargin=0.0,ReserveBalance=0.0,CurrencyID='',PreFundMortgageIn=0.0,PreFundMortgageOut=0.0,FundMortgageIn=0.0,FundMortgageOut=0.0,FundMortgageAvailable=0.0,MortgageableFund=0.0,SpecProductMargin=0.0,SpecProductFrozenMargin=0.0,SpecProductCommission=0.0,SpecProductFrozenCommission=0.0,SpecProductPositionProfit=0.0,SpecProductCloseProfit=0.0,SpecProductPositionProfitByAlg=0.0,SpecProductExchangeMargin=0.0,FrozenSwap=0.0,RemainSwap=0.0):
super(SyncingTradingAccountField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.AccountID=self._to_bytes(AccountID)
self.PreMortgage=float(PreMortgage)
self.PreCredit=float(PreCredit)
self.PreDeposit=float(PreDeposit)
self.PreBalance=float(PreBalance)
self.PreMargin=float(PreMargin)
self.InterestBase=float(InterestBase)
self.Interest=float(Interest)
self.Deposit=float(Deposit)
self.Withdraw=float(Withdraw)
self.FrozenMargin=float(FrozenMargin)
self.FrozenCash=float(FrozenCash)
self.FrozenCommission=float(FrozenCommission)
self.CurrMargin=float(CurrMargin)
self.CashIn=float(CashIn)
self.Commission=float(Commission)
self.CloseProfit=float(CloseProfit)
self.PositionProfit=float(PositionProfit)
self.Balance=float(Balance)
self.Available=float(Available)
self.WithdrawQuota=float(WithdrawQuota)
self.Reserve=float(Reserve)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.Credit=float(Credit)
self.Mortgage=float(Mortgage)
self.ExchangeMargin=float(ExchangeMargin)
self.DeliveryMargin=float(DeliveryMargin)
self.ExchangeDeliveryMargin=float(ExchangeDeliveryMargin)
self.ReserveBalance=float(ReserveBalance)
self.CurrencyID=self._to_bytes(CurrencyID)
self.PreFundMortgageIn=float(PreFundMortgageIn)
self.PreFundMortgageOut=float(PreFundMortgageOut)
self.FundMortgageIn=float(FundMortgageIn)
self.FundMortgageOut=float(FundMortgageOut)
self.FundMortgageAvailable=float(FundMortgageAvailable)
self.MortgageableFund=float(MortgageableFund)
self.SpecProductMargin=float(SpecProductMargin)
self.SpecProductFrozenMargin=float(SpecProductFrozenMargin)
self.SpecProductCommission=float(SpecProductCommission)
self.SpecProductFrozenCommission=float(SpecProductFrozenCommission)
self.SpecProductPositionProfit=float(SpecProductPositionProfit)
self.SpecProductCloseProfit=float(SpecProductCloseProfit)
self.SpecProductPositionProfitByAlg=float(SpecProductPositionProfitByAlg)
self.SpecProductExchangeMargin=float(SpecProductExchangeMargin)
self.FrozenSwap=float(FrozenSwap)
self.RemainSwap=float(RemainSwap)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.AccountID=self._to_bytes(i_tuple[2])
self.PreMortgage=float(i_tuple[3])
self.PreCredit=float(i_tuple[4])
self.PreDeposit=float(i_tuple[5])
self.PreBalance=float(i_tuple[6])
self.PreMargin=float(i_tuple[7])
self.InterestBase=float(i_tuple[8])
self.Interest=float(i_tuple[9])
self.Deposit=float(i_tuple[10])
self.Withdraw=float(i_tuple[11])
self.FrozenMargin=float(i_tuple[12])
self.FrozenCash=float(i_tuple[13])
self.FrozenCommission=float(i_tuple[14])
self.CurrMargin=float(i_tuple[15])
self.CashIn=float(i_tuple[16])
self.Commission=float(i_tuple[17])
self.CloseProfit=float(i_tuple[18])
self.PositionProfit=float(i_tuple[19])
self.Balance=float(i_tuple[20])
self.Available=float(i_tuple[21])
self.WithdrawQuota=float(i_tuple[22])
self.Reserve=float(i_tuple[23])
self.TradingDay=self._to_bytes(i_tuple[24])
self.SettlementID=int(i_tuple[25])
self.Credit=float(i_tuple[26])
self.Mortgage=float(i_tuple[27])
self.ExchangeMargin=float(i_tuple[28])
self.DeliveryMargin=float(i_tuple[29])
self.ExchangeDeliveryMargin=float(i_tuple[30])
self.ReserveBalance=float(i_tuple[31])
self.CurrencyID=self._to_bytes(i_tuple[32])
self.PreFundMortgageIn=float(i_tuple[33])
self.PreFundMortgageOut=float(i_tuple[34])
self.FundMortgageIn=float(i_tuple[35])
self.FundMortgageOut=float(i_tuple[36])
self.FundMortgageAvailable=float(i_tuple[37])
self.MortgageableFund=float(i_tuple[38])
self.SpecProductMargin=float(i_tuple[39])
self.SpecProductFrozenMargin=float(i_tuple[40])
self.SpecProductCommission=float(i_tuple[41])
self.SpecProductFrozenCommission=float(i_tuple[42])
self.SpecProductPositionProfit=float(i_tuple[43])
self.SpecProductCloseProfit=float(i_tuple[44])
self.SpecProductPositionProfitByAlg=float(i_tuple[45])
self.SpecProductExchangeMargin=float(i_tuple[46])
self.FrozenSwap=float(i_tuple[47])
self.RemainSwap=float(i_tuple[48])
class SyncingInvestorPositionField(Base):
"""正在同步中的投资者持仓"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('PosiDirection',ctypes.c_char)# 持仓多空方向
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('PositionDate',ctypes.c_char)# 持仓日期
,('YdPosition',ctypes.c_int)# 上日持仓
,('Position',ctypes.c_int)# 今日持仓
,('LongFrozen',ctypes.c_int)# 多头冻结
,('ShortFrozen',ctypes.c_int)# 空头冻结
,('LongFrozenAmount',ctypes.c_double)# 开仓冻结金额
,('ShortFrozenAmount',ctypes.c_double)# 开仓冻结金额
,('OpenVolume',ctypes.c_int)# 开仓量
,('CloseVolume',ctypes.c_int)# 平仓量
,('OpenAmount',ctypes.c_double)# 开仓金额
,('CloseAmount',ctypes.c_double)# 平仓金额
,('PositionCost',ctypes.c_double)# 持仓成本
,('PreMargin',ctypes.c_double)# 上次占用的保证金
,('UseMargin',ctypes.c_double)# 占用的保证金
,('FrozenMargin',ctypes.c_double)# 冻结的保证金
,('FrozenCash',ctypes.c_double)# 冻结的资金
,('FrozenCommission',ctypes.c_double)# 冻结的手续费
,('CashIn',ctypes.c_double)# 资金差额
,('Commission',ctypes.c_double)# 手续费
,('CloseProfit',ctypes.c_double)# 平仓盈亏
,('PositionProfit',ctypes.c_double)# 持仓盈亏
,('PreSettlementPrice',ctypes.c_double)# 上次结算价
,('SettlementPrice',ctypes.c_double)# 本次结算价
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('OpenCost',ctypes.c_double)# 开仓成本
,('ExchangeMargin',ctypes.c_double)# 交易所保证金
,('CombPosition',ctypes.c_int)# 组合成交形成的持仓
,('CombLongFrozen',ctypes.c_int)# 组合多头冻结
,('CombShortFrozen',ctypes.c_int)# 组合空头冻结
,('CloseProfitByDate',ctypes.c_double)# 逐日盯市平仓盈亏
,('CloseProfitByTrade',ctypes.c_double)# 逐笔对冲平仓盈亏
,('TodayPosition',ctypes.c_int)# 今日持仓
,('MarginRateByMoney',ctypes.c_double)# 保证金率
,('MarginRateByVolume',ctypes.c_double)# 保证金率(按手数)
,('StrikeFrozen',ctypes.c_int)# 执行冻结
,('StrikeFrozenAmount',ctypes.c_double)# 执行冻结金额
,('AbandonFrozen',ctypes.c_int)# 放弃执行冻结
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('YdStrikeFrozen',ctypes.c_int)# 执行冻结的昨仓
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,InstrumentID= '',BrokerID='',InvestorID='',PosiDirection='',HedgeFlag='',PositionDate='',YdPosition=0,Position=0,LongFrozen=0,ShortFrozen=0,LongFrozenAmount=0.0,ShortFrozenAmount=0.0,OpenVolume=0,CloseVolume=0,OpenAmount=0.0,CloseAmount=0.0,PositionCost=0.0,PreMargin=0.0,UseMargin=0.0,FrozenMargin=0.0,FrozenCash=0.0,FrozenCommission=0.0,CashIn=0.0,Commission=0.0,CloseProfit=0.0,PositionProfit=0.0,PreSettlementPrice=0.0,SettlementPrice=0.0,TradingDay='',SettlementID=0,OpenCost=0.0,ExchangeMargin=0.0,CombPosition=0,CombLongFrozen=0,CombShortFrozen=0,CloseProfitByDate=0.0,CloseProfitByTrade=0.0,TodayPosition=0,MarginRateByMoney=0.0,MarginRateByVolume=0.0,StrikeFrozen=0,StrikeFrozenAmount=0.0,AbandonFrozen=0,ExchangeID='',YdStrikeFrozen=0,InvestUnitID=''):
super(SyncingInvestorPositionField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.PosiDirection=self._to_bytes(PosiDirection)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.PositionDate=self._to_bytes(PositionDate)
self.YdPosition=int(YdPosition)
self.Position=int(Position)
self.LongFrozen=int(LongFrozen)
self.ShortFrozen=int(ShortFrozen)
self.LongFrozenAmount=float(LongFrozenAmount)
self.ShortFrozenAmount=float(ShortFrozenAmount)
self.OpenVolume=int(OpenVolume)
self.CloseVolume=int(CloseVolume)
self.OpenAmount=float(OpenAmount)
self.CloseAmount=float(CloseAmount)
self.PositionCost=float(PositionCost)
self.PreMargin=float(PreMargin)
self.UseMargin=float(UseMargin)
self.FrozenMargin=float(FrozenMargin)
self.FrozenCash=float(FrozenCash)
self.FrozenCommission=float(FrozenCommission)
self.CashIn=float(CashIn)
self.Commission=float(Commission)
self.CloseProfit=float(CloseProfit)
self.PositionProfit=float(PositionProfit)
self.PreSettlementPrice=float(PreSettlementPrice)
self.SettlementPrice=float(SettlementPrice)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.OpenCost=float(OpenCost)
self.ExchangeMargin=float(ExchangeMargin)
self.CombPosition=int(CombPosition)
self.CombLongFrozen=int(CombLongFrozen)
self.CombShortFrozen=int(CombShortFrozen)
self.CloseProfitByDate=float(CloseProfitByDate)
self.CloseProfitByTrade=float(CloseProfitByTrade)
self.TodayPosition=int(TodayPosition)
self.MarginRateByMoney=float(MarginRateByMoney)
self.MarginRateByVolume=float(MarginRateByVolume)
self.StrikeFrozen=int(StrikeFrozen)
self.StrikeFrozenAmount=float(StrikeFrozenAmount)
self.AbandonFrozen=int(AbandonFrozen)
self.ExchangeID=self._to_bytes(ExchangeID)
self.YdStrikeFrozen=int(YdStrikeFrozen)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.BrokerID=self._to_bytes(i_tuple[2])
self.InvestorID=self._to_bytes(i_tuple[3])
self.PosiDirection=self._to_bytes(i_tuple[4])
self.HedgeFlag=self._to_bytes(i_tuple[5])
self.PositionDate=self._to_bytes(i_tuple[6])
self.YdPosition=int(i_tuple[7])
self.Position=int(i_tuple[8])
self.LongFrozen=int(i_tuple[9])
self.ShortFrozen=int(i_tuple[10])
self.LongFrozenAmount=float(i_tuple[11])
self.ShortFrozenAmount=float(i_tuple[12])
self.OpenVolume=int(i_tuple[13])
self.CloseVolume=int(i_tuple[14])
self.OpenAmount=float(i_tuple[15])
self.CloseAmount=float(i_tuple[16])
self.PositionCost=float(i_tuple[17])
self.PreMargin=float(i_tuple[18])
self.UseMargin=float(i_tuple[19])
self.FrozenMargin=float(i_tuple[20])
self.FrozenCash=float(i_tuple[21])
self.FrozenCommission=float(i_tuple[22])
self.CashIn=float(i_tuple[23])
self.Commission=float(i_tuple[24])
self.CloseProfit=float(i_tuple[25])
self.PositionProfit=float(i_tuple[26])
self.PreSettlementPrice=float(i_tuple[27])
self.SettlementPrice=float(i_tuple[28])
self.TradingDay=self._to_bytes(i_tuple[29])
self.SettlementID=int(i_tuple[30])
self.OpenCost=float(i_tuple[31])
self.ExchangeMargin=float(i_tuple[32])
self.CombPosition=int(i_tuple[33])
self.CombLongFrozen=int(i_tuple[34])
self.CombShortFrozen=int(i_tuple[35])
self.CloseProfitByDate=float(i_tuple[36])
self.CloseProfitByTrade=float(i_tuple[37])
self.TodayPosition=int(i_tuple[38])
self.MarginRateByMoney=float(i_tuple[39])
self.MarginRateByVolume=float(i_tuple[40])
self.StrikeFrozen=int(i_tuple[41])
self.StrikeFrozenAmount=float(i_tuple[42])
self.AbandonFrozen=int(i_tuple[43])
self.ExchangeID=self._to_bytes(i_tuple[44])
self.YdStrikeFrozen=int(i_tuple[45])
self.InvestUnitID=self._to_bytes(i_tuple[46])
class SyncingInstrumentMarginRateField(Base):
"""正在同步中的合约保证金率"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('LongMarginRatioByMoney',ctypes.c_double)# 多头保证金率
,('LongMarginRatioByVolume',ctypes.c_double)# 多头保证金费
,('ShortMarginRatioByMoney',ctypes.c_double)# 空头保证金率
,('ShortMarginRatioByVolume',ctypes.c_double)# 空头保证金费
,('IsRelative',ctypes.c_int)# 是否相对交易所收取
]
def __init__(self,InstrumentID= '',InvestorRange='',BrokerID='',InvestorID='',HedgeFlag='',LongMarginRatioByMoney=0.0,LongMarginRatioByVolume=0.0,ShortMarginRatioByMoney=0.0,ShortMarginRatioByVolume=0.0,IsRelative=0):
super(SyncingInstrumentMarginRateField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.LongMarginRatioByMoney=float(LongMarginRatioByMoney)
self.LongMarginRatioByVolume=float(LongMarginRatioByVolume)
self.ShortMarginRatioByMoney=float(ShortMarginRatioByMoney)
self.ShortMarginRatioByVolume=float(ShortMarginRatioByVolume)
self.IsRelative=int(IsRelative)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.InvestorID=self._to_bytes(i_tuple[4])
self.HedgeFlag=self._to_bytes(i_tuple[5])
self.LongMarginRatioByMoney=float(i_tuple[6])
self.LongMarginRatioByVolume=float(i_tuple[7])
self.ShortMarginRatioByMoney=float(i_tuple[8])
self.ShortMarginRatioByVolume=float(i_tuple[9])
self.IsRelative=int(i_tuple[10])
class SyncingInstrumentCommissionRateField(Base):
"""正在同步中的合约手续费率"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('OpenRatioByMoney',ctypes.c_double)# 开仓手续费率
,('OpenRatioByVolume',ctypes.c_double)# 开仓手续费
,('CloseRatioByMoney',ctypes.c_double)# 平仓手续费率
,('CloseRatioByVolume',ctypes.c_double)# 平仓手续费
,('CloseTodayRatioByMoney',ctypes.c_double)# 平今手续费率
,('CloseTodayRatioByVolume',ctypes.c_double)# 平今手续费
]
def __init__(self,InstrumentID= '',InvestorRange='',BrokerID='',InvestorID='',OpenRatioByMoney=0.0,OpenRatioByVolume=0.0,CloseRatioByMoney=0.0,CloseRatioByVolume=0.0,CloseTodayRatioByMoney=0.0,CloseTodayRatioByVolume=0.0):
super(SyncingInstrumentCommissionRateField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.OpenRatioByMoney=float(OpenRatioByMoney)
self.OpenRatioByVolume=float(OpenRatioByVolume)
self.CloseRatioByMoney=float(CloseRatioByMoney)
self.CloseRatioByVolume=float(CloseRatioByVolume)
self.CloseTodayRatioByMoney=float(CloseTodayRatioByMoney)
self.CloseTodayRatioByVolume=float(CloseTodayRatioByVolume)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.InvestorID=self._to_bytes(i_tuple[4])
self.OpenRatioByMoney=float(i_tuple[5])
self.OpenRatioByVolume=float(i_tuple[6])
self.CloseRatioByMoney=float(i_tuple[7])
self.CloseRatioByVolume=float(i_tuple[8])
self.CloseTodayRatioByMoney=float(i_tuple[9])
self.CloseTodayRatioByVolume=float(i_tuple[10])
class SyncingInstrumentTradingRightField(Base):
"""正在同步中的合约交易权限"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('TradingRight',ctypes.c_char)# 交易权限
]
def __init__(self,InstrumentID= '',InvestorRange='',BrokerID='',InvestorID='',TradingRight=''):
super(SyncingInstrumentTradingRightField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.TradingRight=self._to_bytes(TradingRight)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.InvestorID=self._to_bytes(i_tuple[4])
self.TradingRight=self._to_bytes(i_tuple[5])
class QryOrderField(Base):
"""查询报单"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('OrderSysID',ctypes.c_char*21)# 报单编号
,('InsertTimeStart',ctypes.c_char*9)# 开始时间
,('InsertTimeEnd',ctypes.c_char*9)# 结束时间
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ExchangeID='',OrderSysID='',InsertTimeStart='',InsertTimeEnd='',InvestUnitID=''):
super(QryOrderField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.OrderSysID=self._to_bytes(OrderSysID)
self.InsertTimeStart=self._to_bytes(InsertTimeStart)
self.InsertTimeEnd=self._to_bytes(InsertTimeEnd)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.OrderSysID=self._to_bytes(i_tuple[5])
self.InsertTimeStart=self._to_bytes(i_tuple[6])
self.InsertTimeEnd=self._to_bytes(i_tuple[7])
self.InvestUnitID=self._to_bytes(i_tuple[8])
class QryTradeField(Base):
"""查询成交"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('TradeID',ctypes.c_char*21)# 成交编号
,('TradeTimeStart',ctypes.c_char*9)# 开始时间
,('TradeTimeEnd',ctypes.c_char*9)# 结束时间
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ExchangeID='',TradeID='',TradeTimeStart='',TradeTimeEnd='',InvestUnitID=''):
super(QryTradeField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.TradeID=self._to_bytes(TradeID)
self.TradeTimeStart=self._to_bytes(TradeTimeStart)
self.TradeTimeEnd=self._to_bytes(TradeTimeEnd)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.TradeID=self._to_bytes(i_tuple[5])
self.TradeTimeStart=self._to_bytes(i_tuple[6])
self.TradeTimeEnd=self._to_bytes(i_tuple[7])
self.InvestUnitID=self._to_bytes(i_tuple[8])
class QryInvestorPositionField(Base):
"""查询投资者持仓"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ExchangeID='',InvestUnitID=''):
super(QryInvestorPositionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.InvestUnitID=self._to_bytes(i_tuple[5])
class QryTradingAccountField(Base):
"""查询资金账户"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('BizType',ctypes.c_char)# 业务类型
,('AccountID',ctypes.c_char*13)# 投资者帐号
]
def __init__(self,BrokerID= '',InvestorID='',CurrencyID='',BizType='',AccountID=''):
super(QryTradingAccountField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.CurrencyID=self._to_bytes(CurrencyID)
self.BizType=self._to_bytes(BizType)
self.AccountID=self._to_bytes(AccountID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.CurrencyID=self._to_bytes(i_tuple[3])
self.BizType=self._to_bytes(i_tuple[4])
self.AccountID=self._to_bytes(i_tuple[5])
class QryInvestorField(Base):
"""查询投资者"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
]
def __init__(self,BrokerID= '',InvestorID=''):
super(QryInvestorField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
class QryTradingCodeField(Base):
"""查询交易编码"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ClientIDType',ctypes.c_char)# 交易编码类型
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',ExchangeID='',ClientID='',ClientIDType='',InvestUnitID=''):
super(QryTradingCodeField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ClientID=self._to_bytes(ClientID)
self.ClientIDType=self._to_bytes(ClientIDType)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
self.ClientID=self._to_bytes(i_tuple[4])
self.ClientIDType=self._to_bytes(i_tuple[5])
self.InvestUnitID=self._to_bytes(i_tuple[6])
class QryInvestorGroupField(Base):
"""查询投资者组"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
]
def __init__(self,BrokerID= ''):
super(QryInvestorGroupField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
class QryInstrumentMarginRateField(Base):
"""查询合约保证金率"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',HedgeFlag='',ExchangeID='',InvestUnitID=''):
super(QryInstrumentMarginRateField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.HedgeFlag=self._to_bytes(i_tuple[4])
self.ExchangeID=self._to_bytes(i_tuple[5])
self.InvestUnitID=self._to_bytes(i_tuple[6])
class QryInstrumentCommissionRateField(Base):
"""查询手续费率"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ExchangeID='',InvestUnitID=''):
super(QryInstrumentCommissionRateField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.InvestUnitID=self._to_bytes(i_tuple[5])
class QryInstrumentTradingRightField(Base):
"""查询合约交易权限"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID=''):
super(QryInstrumentTradingRightField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
class QryBrokerField(Base):
"""查询经纪公司"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
]
def __init__(self,BrokerID= ''):
super(QryBrokerField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
class QryTraderField(Base):
"""查询交易员"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
]
def __init__(self,ExchangeID= '',ParticipantID='',TraderID=''):
super(QryTraderField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.TraderID=self._to_bytes(TraderID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.ParticipantID=self._to_bytes(i_tuple[2])
self.TraderID=self._to_bytes(i_tuple[3])
class QrySuperUserFunctionField(Base):
"""查询管理用户功能权限"""
_fields_ = [
('UserID',ctypes.c_char*16)# ///用户代码
]
def __init__(self,UserID= ''):
super(QrySuperUserFunctionField,self).__init__()
self.UserID=self._to_bytes(UserID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.UserID=self._to_bytes(i_tuple[1])
class QryUserSessionField(Base):
"""查询用户会话"""
_fields_ = [
('FrontID',ctypes.c_int)# ///前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
]
def __init__(self,FrontID= 0,SessionID=0,BrokerID='',UserID=''):
super(QryUserSessionField,self).__init__()
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.FrontID=int(i_tuple[1])
self.SessionID=int(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.UserID=self._to_bytes(i_tuple[4])
class QryPartBrokerField(Base):
"""查询经纪公司会员代码"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
]
def __init__(self,ExchangeID= '',BrokerID='',ParticipantID=''):
super(QryPartBrokerField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.BrokerID=self._to_bytes(BrokerID)
self.ParticipantID=self._to_bytes(ParticipantID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.BrokerID=self._to_bytes(i_tuple[2])
self.ParticipantID=self._to_bytes(i_tuple[3])
class QryFrontStatusField(Base):
"""查询前置状态"""
_fields_ = [
('FrontID',ctypes.c_int)# ///前置编号
]
def __init__(self,FrontID= 0):
super(QryFrontStatusField,self).__init__()
self.FrontID=int(FrontID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.FrontID=int(i_tuple[1])
class QryExchangeOrderField(Base):
"""查询交易所报单"""
_fields_ = [
('ParticipantID',ctypes.c_char*11)# ///会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
]
def __init__(self,ParticipantID= '',ClientID='',ExchangeInstID='',ExchangeID='',TraderID=''):
super(QryExchangeOrderField,self).__init__()
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.TraderID=self._to_bytes(TraderID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ParticipantID=self._to_bytes(i_tuple[1])
self.ClientID=self._to_bytes(i_tuple[2])
self.ExchangeInstID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.TraderID=self._to_bytes(i_tuple[5])
class QryOrderActionField(Base):
"""查询报单操作"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
]
def __init__(self,BrokerID= '',InvestorID='',ExchangeID=''):
super(QryOrderActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
class QryExchangeOrderActionField(Base):
"""查询交易所报单操作"""
_fields_ = [
('ParticipantID',ctypes.c_char*11)# ///会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
]
def __init__(self,ParticipantID= '',ClientID='',ExchangeID='',TraderID=''):
super(QryExchangeOrderActionField,self).__init__()
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.TraderID=self._to_bytes(TraderID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ParticipantID=self._to_bytes(i_tuple[1])
self.ClientID=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
self.TraderID=self._to_bytes(i_tuple[4])
class QrySuperUserField(Base):
"""查询管理用户"""
_fields_ = [
('UserID',ctypes.c_char*16)# ///用户代码
]
def __init__(self,UserID= ''):
super(QrySuperUserField,self).__init__()
self.UserID=self._to_bytes(UserID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.UserID=self._to_bytes(i_tuple[1])
class QryExchangeField(Base):
"""查询交易所"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
]
def __init__(self,ExchangeID= ''):
super(QryExchangeField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
class QryProductField(Base):
"""查询产品"""
_fields_ = [
('ProductID',ctypes.c_char*31)# ///产品代码
,('ProductClass',ctypes.c_char)# 产品类型
,('ExchangeID',ctypes.c_char*9)# 交易所代码
]
def __init__(self,ProductID= '',ProductClass='',ExchangeID=''):
super(QryProductField,self).__init__()
self.ProductID=self._to_bytes(ProductID)
self.ProductClass=self._to_bytes(ProductClass)
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ProductID=self._to_bytes(i_tuple[1])
self.ProductClass=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
class QryInstrumentField(Base):
"""查询合约"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('ProductID',ctypes.c_char*31)# 产品代码
]
def __init__(self,InstrumentID= '',ExchangeID='',ExchangeInstID='',ProductID=''):
super(QryInstrumentField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.ProductID=self._to_bytes(ProductID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.ExchangeID=self._to_bytes(i_tuple[2])
self.ExchangeInstID=self._to_bytes(i_tuple[3])
self.ProductID=self._to_bytes(i_tuple[4])
class QryDepthMarketDataField(Base):
"""查询行情"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
]
def __init__(self,InstrumentID= '',ExchangeID=''):
super(QryDepthMarketDataField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.ExchangeID=self._to_bytes(i_tuple[2])
class QryBrokerUserField(Base):
"""查询经纪公司用户"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
]
def __init__(self,BrokerID= '',UserID=''):
super(QryBrokerUserField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
class QryBrokerUserFunctionField(Base):
"""查询经纪公司用户权限"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
]
def __init__(self,BrokerID= '',UserID=''):
super(QryBrokerUserFunctionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
class QryTraderOfferField(Base):
"""查询交易员报盘机"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
]
def __init__(self,ExchangeID= '',ParticipantID='',TraderID=''):
super(QryTraderOfferField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.TraderID=self._to_bytes(TraderID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.ParticipantID=self._to_bytes(i_tuple[2])
self.TraderID=self._to_bytes(i_tuple[3])
class QrySyncDepositField(Base):
"""查询出入金流水"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('DepositSeqNo',ctypes.c_char*15)# 出入金流水号
]
def __init__(self,BrokerID= '',DepositSeqNo=''):
super(QrySyncDepositField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.DepositSeqNo=self._to_bytes(DepositSeqNo)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.DepositSeqNo=self._to_bytes(i_tuple[2])
class QrySettlementInfoField(Base):
"""查询投资者结算结果"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('TradingDay',ctypes.c_char*9)# 交易日
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('CurrencyID',ctypes.c_char*4)# 币种代码
]
def __init__(self,BrokerID= '',InvestorID='',TradingDay='',AccountID='',CurrencyID=''):
super(QrySettlementInfoField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.TradingDay=self._to_bytes(TradingDay)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.TradingDay=self._to_bytes(i_tuple[3])
self.AccountID=self._to_bytes(i_tuple[4])
self.CurrencyID=self._to_bytes(i_tuple[5])
class QryExchangeMarginRateField(Base):
"""查询交易所保证金率"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('ExchangeID',ctypes.c_char*9)# 交易所代码
]
def __init__(self,BrokerID= '',InstrumentID='',HedgeFlag='',ExchangeID=''):
super(QryExchangeMarginRateField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InstrumentID=self._to_bytes(i_tuple[2])
self.HedgeFlag=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
class QryExchangeMarginRateAdjustField(Base):
"""查询交易所调整保证金率"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('HedgeFlag',ctypes.c_char)# 投机套保标志
]
def __init__(self,BrokerID= '',InstrumentID='',HedgeFlag=''):
super(QryExchangeMarginRateAdjustField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.HedgeFlag=self._to_bytes(HedgeFlag)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InstrumentID=self._to_bytes(i_tuple[2])
self.HedgeFlag=self._to_bytes(i_tuple[3])
class QryExchangeRateField(Base):
"""查询汇率"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('FromCurrencyID',ctypes.c_char*4)# 源币种
,('ToCurrencyID',ctypes.c_char*4)# 目标币种
]
def __init__(self,BrokerID= '',FromCurrencyID='',ToCurrencyID=''):
super(QryExchangeRateField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.FromCurrencyID=self._to_bytes(FromCurrencyID)
self.ToCurrencyID=self._to_bytes(ToCurrencyID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.FromCurrencyID=self._to_bytes(i_tuple[2])
self.ToCurrencyID=self._to_bytes(i_tuple[3])
class QrySyncFundMortgageField(Base):
"""查询货币质押流水"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('MortgageSeqNo',ctypes.c_char*15)# 货币质押流水号
]
def __init__(self,BrokerID= '',MortgageSeqNo=''):
super(QrySyncFundMortgageField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.MortgageSeqNo=self._to_bytes(MortgageSeqNo)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.MortgageSeqNo=self._to_bytes(i_tuple[2])
class QryHisOrderField(Base):
"""查询报单"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('OrderSysID',ctypes.c_char*21)# 报单编号
,('InsertTimeStart',ctypes.c_char*9)# 开始时间
,('InsertTimeEnd',ctypes.c_char*9)# 结束时间
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ExchangeID='',OrderSysID='',InsertTimeStart='',InsertTimeEnd='',TradingDay='',SettlementID=0):
super(QryHisOrderField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.OrderSysID=self._to_bytes(OrderSysID)
self.InsertTimeStart=self._to_bytes(InsertTimeStart)
self.InsertTimeEnd=self._to_bytes(InsertTimeEnd)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.OrderSysID=self._to_bytes(i_tuple[5])
self.InsertTimeStart=self._to_bytes(i_tuple[6])
self.InsertTimeEnd=self._to_bytes(i_tuple[7])
self.TradingDay=self._to_bytes(i_tuple[8])
self.SettlementID=int(i_tuple[9])
class OptionInstrMiniMarginField(Base):
"""当前期权合约最小保证金"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('MinMargin',ctypes.c_double)# 单位(手)期权合约最小保证金
,('ValueMethod',ctypes.c_char)# 取值方式
,('IsRelative',ctypes.c_int)# 是否跟随交易所收取
]
def __init__(self,InstrumentID= '',InvestorRange='',BrokerID='',InvestorID='',MinMargin=0.0,ValueMethod='',IsRelative=0):
super(OptionInstrMiniMarginField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.MinMargin=float(MinMargin)
self.ValueMethod=self._to_bytes(ValueMethod)
self.IsRelative=int(IsRelative)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.InvestorID=self._to_bytes(i_tuple[4])
self.MinMargin=float(i_tuple[5])
self.ValueMethod=self._to_bytes(i_tuple[6])
self.IsRelative=int(i_tuple[7])
class OptionInstrMarginAdjustField(Base):
"""当前期权合约保证金调整系数"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('SShortMarginRatioByMoney',ctypes.c_double)# 投机空头保证金调整系数
,('SShortMarginRatioByVolume',ctypes.c_double)# 投机空头保证金调整系数
,('HShortMarginRatioByMoney',ctypes.c_double)# 保值空头保证金调整系数
,('HShortMarginRatioByVolume',ctypes.c_double)# 保值空头保证金调整系数
,('AShortMarginRatioByMoney',ctypes.c_double)# 套利空头保证金调整系数
,('AShortMarginRatioByVolume',ctypes.c_double)# 套利空头保证金调整系数
,('IsRelative',ctypes.c_int)# 是否跟随交易所收取
,('MShortMarginRatioByMoney',ctypes.c_double)# 做市商空头保证金调整系数
,('MShortMarginRatioByVolume',ctypes.c_double)# 做市商空头保证金调整系数
]
def __init__(self,InstrumentID= '',InvestorRange='',BrokerID='',InvestorID='',SShortMarginRatioByMoney=0.0,SShortMarginRatioByVolume=0.0,HShortMarginRatioByMoney=0.0,HShortMarginRatioByVolume=0.0,AShortMarginRatioByMoney=0.0,AShortMarginRatioByVolume=0.0,IsRelative=0,MShortMarginRatioByMoney=0.0,MShortMarginRatioByVolume=0.0):
super(OptionInstrMarginAdjustField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.SShortMarginRatioByMoney=float(SShortMarginRatioByMoney)
self.SShortMarginRatioByVolume=float(SShortMarginRatioByVolume)
self.HShortMarginRatioByMoney=float(HShortMarginRatioByMoney)
self.HShortMarginRatioByVolume=float(HShortMarginRatioByVolume)
self.AShortMarginRatioByMoney=float(AShortMarginRatioByMoney)
self.AShortMarginRatioByVolume=float(AShortMarginRatioByVolume)
self.IsRelative=int(IsRelative)
self.MShortMarginRatioByMoney=float(MShortMarginRatioByMoney)
self.MShortMarginRatioByVolume=float(MShortMarginRatioByVolume)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.InvestorID=self._to_bytes(i_tuple[4])
self.SShortMarginRatioByMoney=float(i_tuple[5])
self.SShortMarginRatioByVolume=float(i_tuple[6])
self.HShortMarginRatioByMoney=float(i_tuple[7])
self.HShortMarginRatioByVolume=float(i_tuple[8])
self.AShortMarginRatioByMoney=float(i_tuple[9])
self.AShortMarginRatioByVolume=float(i_tuple[10])
self.IsRelative=int(i_tuple[11])
self.MShortMarginRatioByMoney=float(i_tuple[12])
self.MShortMarginRatioByVolume=float(i_tuple[13])
class OptionInstrCommRateField(Base):
"""当前期权合约手续费的详细内容"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('OpenRatioByMoney',ctypes.c_double)# 开仓手续费率
,('OpenRatioByVolume',ctypes.c_double)# 开仓手续费
,('CloseRatioByMoney',ctypes.c_double)# 平仓手续费率
,('CloseRatioByVolume',ctypes.c_double)# 平仓手续费
,('CloseTodayRatioByMoney',ctypes.c_double)# 平今手续费率
,('CloseTodayRatioByVolume',ctypes.c_double)# 平今手续费
,('StrikeRatioByMoney',ctypes.c_double)# 执行手续费率
,('StrikeRatioByVolume',ctypes.c_double)# 执行手续费
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,InstrumentID= '',InvestorRange='',BrokerID='',InvestorID='',OpenRatioByMoney=0.0,OpenRatioByVolume=0.0,CloseRatioByMoney=0.0,CloseRatioByVolume=0.0,CloseTodayRatioByMoney=0.0,CloseTodayRatioByVolume=0.0,StrikeRatioByMoney=0.0,StrikeRatioByVolume=0.0,ExchangeID='',InvestUnitID=''):
super(OptionInstrCommRateField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.OpenRatioByMoney=float(OpenRatioByMoney)
self.OpenRatioByVolume=float(OpenRatioByVolume)
self.CloseRatioByMoney=float(CloseRatioByMoney)
self.CloseRatioByVolume=float(CloseRatioByVolume)
self.CloseTodayRatioByMoney=float(CloseTodayRatioByMoney)
self.CloseTodayRatioByVolume=float(CloseTodayRatioByVolume)
self.StrikeRatioByMoney=float(StrikeRatioByMoney)
self.StrikeRatioByVolume=float(StrikeRatioByVolume)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.InvestorID=self._to_bytes(i_tuple[4])
self.OpenRatioByMoney=float(i_tuple[5])
self.OpenRatioByVolume=float(i_tuple[6])
self.CloseRatioByMoney=float(i_tuple[7])
self.CloseRatioByVolume=float(i_tuple[8])
self.CloseTodayRatioByMoney=float(i_tuple[9])
self.CloseTodayRatioByVolume=float(i_tuple[10])
self.StrikeRatioByMoney=float(i_tuple[11])
self.StrikeRatioByVolume=float(i_tuple[12])
self.ExchangeID=self._to_bytes(i_tuple[13])
self.InvestUnitID=self._to_bytes(i_tuple[14])
class OptionInstrTradeCostField(Base):
"""期权交易成本"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('FixedMargin',ctypes.c_double)# 期权合约保证金不变部分
,('MiniMargin',ctypes.c_double)# 期权合约最小保证金
,('Royalty',ctypes.c_double)# 期权合约权利金
,('ExchFixedMargin',ctypes.c_double)# 交易所期权合约保证金不变部分
,('ExchMiniMargin',ctypes.c_double)# 交易所期权合约最小保证金
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',HedgeFlag='',FixedMargin=0.0,MiniMargin=0.0,Royalty=0.0,ExchFixedMargin=0.0,ExchMiniMargin=0.0,ExchangeID='',InvestUnitID=''):
super(OptionInstrTradeCostField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.FixedMargin=float(FixedMargin)
self.MiniMargin=float(MiniMargin)
self.Royalty=float(Royalty)
self.ExchFixedMargin=float(ExchFixedMargin)
self.ExchMiniMargin=float(ExchMiniMargin)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.HedgeFlag=self._to_bytes(i_tuple[4])
self.FixedMargin=float(i_tuple[5])
self.MiniMargin=float(i_tuple[6])
self.Royalty=float(i_tuple[7])
self.ExchFixedMargin=float(i_tuple[8])
self.ExchMiniMargin=float(i_tuple[9])
self.ExchangeID=self._to_bytes(i_tuple[10])
self.InvestUnitID=self._to_bytes(i_tuple[11])
class QryOptionInstrTradeCostField(Base):
"""期权交易成本查询"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('InputPrice',ctypes.c_double)# 期权合约报价
,('UnderlyingPrice',ctypes.c_double)# 标的价格,填0则用昨结算价
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',HedgeFlag='',InputPrice=0.0,UnderlyingPrice=0.0,ExchangeID='',InvestUnitID=''):
super(QryOptionInstrTradeCostField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.InputPrice=float(InputPrice)
self.UnderlyingPrice=float(UnderlyingPrice)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.HedgeFlag=self._to_bytes(i_tuple[4])
self.InputPrice=float(i_tuple[5])
self.UnderlyingPrice=float(i_tuple[6])
self.ExchangeID=self._to_bytes(i_tuple[7])
self.InvestUnitID=self._to_bytes(i_tuple[8])
class QryOptionInstrCommRateField(Base):
"""期权手续费率查询"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ExchangeID='',InvestUnitID=''):
super(QryOptionInstrCommRateField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.InvestUnitID=self._to_bytes(i_tuple[5])
class IndexPriceField(Base):
"""股指现货指数"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ClosePrice',ctypes.c_double)# 指数现货收盘价
]
def __init__(self,BrokerID= '',InstrumentID='',ClosePrice=0.0):
super(IndexPriceField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ClosePrice=float(ClosePrice)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InstrumentID=self._to_bytes(i_tuple[2])
self.ClosePrice=float(i_tuple[3])
class InputExecOrderField(Base):
"""输入的执行宣告"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExecOrderRef',ctypes.c_char*13)# 执行宣告引用
,('UserID',ctypes.c_char*16)# 用户代码
,('Volume',ctypes.c_int)# 数量
,('RequestID',ctypes.c_int)# 请求编号
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('OffsetFlag',ctypes.c_char)# 开平标志
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('ActionType',ctypes.c_char)# 执行类型
,('PosiDirection',ctypes.c_char)# 保留头寸申请的持仓方向
,('ReservePositionFlag',ctypes.c_char)# 期权行权后是否保留期货头寸的标记,该字段已废弃
,('CloseFlag',ctypes.c_char)# 期权行权后生成的头寸是否自动平仓
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('AccountID',ctypes.c_char*13)# 资金账号
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('ClientID',ctypes.c_char*11)# 交易编码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ExecOrderRef='',UserID='',Volume=0,RequestID=0,BusinessUnit='',OffsetFlag='',HedgeFlag='',ActionType='',PosiDirection='',ReservePositionFlag='',CloseFlag='',ExchangeID='',InvestUnitID='',AccountID='',CurrencyID='',ClientID='',IPAddress='',MacAddress=''):
super(InputExecOrderField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExecOrderRef=self._to_bytes(ExecOrderRef)
self.UserID=self._to_bytes(UserID)
self.Volume=int(Volume)
self.RequestID=int(RequestID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.OffsetFlag=self._to_bytes(OffsetFlag)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.ActionType=self._to_bytes(ActionType)
self.PosiDirection=self._to_bytes(PosiDirection)
self.ReservePositionFlag=self._to_bytes(ReservePositionFlag)
self.CloseFlag=self._to_bytes(CloseFlag)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
self.ClientID=self._to_bytes(ClientID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ExecOrderRef=self._to_bytes(i_tuple[4])
self.UserID=self._to_bytes(i_tuple[5])
self.Volume=int(i_tuple[6])
self.RequestID=int(i_tuple[7])
self.BusinessUnit=self._to_bytes(i_tuple[8])
self.OffsetFlag=self._to_bytes(i_tuple[9])
self.HedgeFlag=self._to_bytes(i_tuple[10])
self.ActionType=self._to_bytes(i_tuple[11])
self.PosiDirection=self._to_bytes(i_tuple[12])
self.ReservePositionFlag=self._to_bytes(i_tuple[13])
self.CloseFlag=self._to_bytes(i_tuple[14])
self.ExchangeID=self._to_bytes(i_tuple[15])
self.InvestUnitID=self._to_bytes(i_tuple[16])
self.AccountID=self._to_bytes(i_tuple[17])
self.CurrencyID=self._to_bytes(i_tuple[18])
self.ClientID=self._to_bytes(i_tuple[19])
self.IPAddress=self._to_bytes(i_tuple[20])
self.MacAddress=self._to_bytes(i_tuple[21])
class InputExecOrderActionField(Base):
"""输入执行宣告操作"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('ExecOrderActionRef',ctypes.c_int)# 执行宣告操作引用
,('ExecOrderRef',ctypes.c_char*13)# 执行宣告引用
,('RequestID',ctypes.c_int)# 请求编号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ExecOrderSysID',ctypes.c_char*21)# 执行宣告操作编号
,('ActionFlag',ctypes.c_char)# 操作标志
,('UserID',ctypes.c_char*16)# 用户代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',ExecOrderActionRef=0,ExecOrderRef='',RequestID=0,FrontID=0,SessionID=0,ExchangeID='',ExecOrderSysID='',ActionFlag='',UserID='',InstrumentID='',InvestUnitID='',IPAddress='',MacAddress=''):
super(InputExecOrderActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.ExecOrderActionRef=int(ExecOrderActionRef)
self.ExecOrderRef=self._to_bytes(ExecOrderRef)
self.RequestID=int(RequestID)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ExecOrderSysID=self._to_bytes(ExecOrderSysID)
self.ActionFlag=self._to_bytes(ActionFlag)
self.UserID=self._to_bytes(UserID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.ExecOrderActionRef=int(i_tuple[3])
self.ExecOrderRef=self._to_bytes(i_tuple[4])
self.RequestID=int(i_tuple[5])
self.FrontID=int(i_tuple[6])
self.SessionID=int(i_tuple[7])
self.ExchangeID=self._to_bytes(i_tuple[8])
self.ExecOrderSysID=self._to_bytes(i_tuple[9])
self.ActionFlag=self._to_bytes(i_tuple[10])
self.UserID=self._to_bytes(i_tuple[11])
self.InstrumentID=self._to_bytes(i_tuple[12])
self.InvestUnitID=self._to_bytes(i_tuple[13])
self.IPAddress=self._to_bytes(i_tuple[14])
self.MacAddress=self._to_bytes(i_tuple[15])
class ExecOrderField(Base):
"""执行宣告"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExecOrderRef',ctypes.c_char*13)# 执行宣告引用
,('UserID',ctypes.c_char*16)# 用户代码
,('Volume',ctypes.c_int)# 数量
,('RequestID',ctypes.c_int)# 请求编号
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('OffsetFlag',ctypes.c_char)# 开平标志
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('ActionType',ctypes.c_char)# 执行类型
,('PosiDirection',ctypes.c_char)# 保留头寸申请的持仓方向
,('ReservePositionFlag',ctypes.c_char)# 期权行权后是否保留期货头寸的标记,该字段已废弃
,('CloseFlag',ctypes.c_char)# 期权行权后生成的头寸是否自动平仓
,('ExecOrderLocalID',ctypes.c_char*13)# 本地执行宣告编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('OrderSubmitStatus',ctypes.c_char)# 执行宣告提交状态
,('NotifySequence',ctypes.c_int)# 报单提示序号
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('ExecOrderSysID',ctypes.c_char*21)# 执行宣告编号
,('InsertDate',ctypes.c_char*9)# 报单日期
,('InsertTime',ctypes.c_char*9)# 插入时间
,('CancelTime',ctypes.c_char*9)# 撤销时间
,('ExecResult',ctypes.c_char)# 执行结果
,('ClearingPartID',ctypes.c_char*11)# 结算会员编号
,('SequenceNo',ctypes.c_int)# 序号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('UserProductInfo',ctypes.c_char*11)# 用户端产品信息
,('StatusMsg',ctypes.c_char*81)# 状态信息
,('ActiveUserID',ctypes.c_char*16)# 操作用户代码
,('BrokerExecOrderSeq',ctypes.c_int)# 经纪公司报单编号
,('BranchID',ctypes.c_char*9)# 营业部编号
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('AccountID',ctypes.c_char*13)# 资金账号
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ExecOrderRef='',UserID='',Volume=0,RequestID=0,BusinessUnit='',OffsetFlag='',HedgeFlag='',ActionType='',PosiDirection='',ReservePositionFlag='',CloseFlag='',ExecOrderLocalID='',ExchangeID='',ParticipantID='',ClientID='',ExchangeInstID='',TraderID='',InstallID=0,OrderSubmitStatus='',NotifySequence=0,TradingDay='',SettlementID=0,ExecOrderSysID='',InsertDate='',InsertTime='',CancelTime='',ExecResult='',ClearingPartID='',SequenceNo=0,FrontID=0,SessionID=0,UserProductInfo='',StatusMsg='',ActiveUserID='',BrokerExecOrderSeq=0,BranchID='',InvestUnitID='',AccountID='',CurrencyID='',IPAddress='',MacAddress=''):
super(ExecOrderField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExecOrderRef=self._to_bytes(ExecOrderRef)
self.UserID=self._to_bytes(UserID)
self.Volume=int(Volume)
self.RequestID=int(RequestID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.OffsetFlag=self._to_bytes(OffsetFlag)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.ActionType=self._to_bytes(ActionType)
self.PosiDirection=self._to_bytes(PosiDirection)
self.ReservePositionFlag=self._to_bytes(ReservePositionFlag)
self.CloseFlag=self._to_bytes(CloseFlag)
self.ExecOrderLocalID=self._to_bytes(ExecOrderLocalID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.OrderSubmitStatus=self._to_bytes(OrderSubmitStatus)
self.NotifySequence=int(NotifySequence)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.ExecOrderSysID=self._to_bytes(ExecOrderSysID)
self.InsertDate=self._to_bytes(InsertDate)
self.InsertTime=self._to_bytes(InsertTime)
self.CancelTime=self._to_bytes(CancelTime)
self.ExecResult=self._to_bytes(ExecResult)
self.ClearingPartID=self._to_bytes(ClearingPartID)
self.SequenceNo=int(SequenceNo)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.UserProductInfo=self._to_bytes(UserProductInfo)
self.StatusMsg=self._to_bytes(StatusMsg)
self.ActiveUserID=self._to_bytes(ActiveUserID)
self.BrokerExecOrderSeq=int(BrokerExecOrderSeq)
self.BranchID=self._to_bytes(BranchID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ExecOrderRef=self._to_bytes(i_tuple[4])
self.UserID=self._to_bytes(i_tuple[5])
self.Volume=int(i_tuple[6])
self.RequestID=int(i_tuple[7])
self.BusinessUnit=self._to_bytes(i_tuple[8])
self.OffsetFlag=self._to_bytes(i_tuple[9])
self.HedgeFlag=self._to_bytes(i_tuple[10])
self.ActionType=self._to_bytes(i_tuple[11])
self.PosiDirection=self._to_bytes(i_tuple[12])
self.ReservePositionFlag=self._to_bytes(i_tuple[13])
self.CloseFlag=self._to_bytes(i_tuple[14])
self.ExecOrderLocalID=self._to_bytes(i_tuple[15])
self.ExchangeID=self._to_bytes(i_tuple[16])
self.ParticipantID=self._to_bytes(i_tuple[17])
self.ClientID=self._to_bytes(i_tuple[18])
self.ExchangeInstID=self._to_bytes(i_tuple[19])
self.TraderID=self._to_bytes(i_tuple[20])
self.InstallID=int(i_tuple[21])
self.OrderSubmitStatus=self._to_bytes(i_tuple[22])
self.NotifySequence=int(i_tuple[23])
self.TradingDay=self._to_bytes(i_tuple[24])
self.SettlementID=int(i_tuple[25])
self.ExecOrderSysID=self._to_bytes(i_tuple[26])
self.InsertDate=self._to_bytes(i_tuple[27])
self.InsertTime=self._to_bytes(i_tuple[28])
self.CancelTime=self._to_bytes(i_tuple[29])
self.ExecResult=self._to_bytes(i_tuple[30])
self.ClearingPartID=self._to_bytes(i_tuple[31])
self.SequenceNo=int(i_tuple[32])
self.FrontID=int(i_tuple[33])
self.SessionID=int(i_tuple[34])
self.UserProductInfo=self._to_bytes(i_tuple[35])
self.StatusMsg=self._to_bytes(i_tuple[36])
self.ActiveUserID=self._to_bytes(i_tuple[37])
self.BrokerExecOrderSeq=int(i_tuple[38])
self.BranchID=self._to_bytes(i_tuple[39])
self.InvestUnitID=self._to_bytes(i_tuple[40])
self.AccountID=self._to_bytes(i_tuple[41])
self.CurrencyID=self._to_bytes(i_tuple[42])
self.IPAddress=self._to_bytes(i_tuple[43])
self.MacAddress=self._to_bytes(i_tuple[44])
class ExecOrderActionField(Base):
"""执行宣告操作"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('ExecOrderActionRef',ctypes.c_int)# 执行宣告操作引用
,('ExecOrderRef',ctypes.c_char*13)# 执行宣告引用
,('RequestID',ctypes.c_int)# 请求编号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ExecOrderSysID',ctypes.c_char*21)# 执行宣告操作编号
,('ActionFlag',ctypes.c_char)# 操作标志
,('ActionDate',ctypes.c_char*9)# 操作日期
,('ActionTime',ctypes.c_char*9)# 操作时间
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('ExecOrderLocalID',ctypes.c_char*13)# 本地执行宣告编号
,('ActionLocalID',ctypes.c_char*13)# 操作本地编号
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('OrderActionStatus',ctypes.c_char)# 报单操作状态
,('UserID',ctypes.c_char*16)# 用户代码
,('ActionType',ctypes.c_char)# 执行类型
,('StatusMsg',ctypes.c_char*81)# 状态信息
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('BranchID',ctypes.c_char*9)# 营业部编号
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',ExecOrderActionRef=0,ExecOrderRef='',RequestID=0,FrontID=0,SessionID=0,ExchangeID='',ExecOrderSysID='',ActionFlag='',ActionDate='',ActionTime='',TraderID='',InstallID=0,ExecOrderLocalID='',ActionLocalID='',ParticipantID='',ClientID='',BusinessUnit='',OrderActionStatus='',UserID='',ActionType='',StatusMsg='',InstrumentID='',BranchID='',InvestUnitID='',IPAddress='',MacAddress=''):
super(ExecOrderActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.ExecOrderActionRef=int(ExecOrderActionRef)
self.ExecOrderRef=self._to_bytes(ExecOrderRef)
self.RequestID=int(RequestID)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ExecOrderSysID=self._to_bytes(ExecOrderSysID)
self.ActionFlag=self._to_bytes(ActionFlag)
self.ActionDate=self._to_bytes(ActionDate)
self.ActionTime=self._to_bytes(ActionTime)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.ExecOrderLocalID=self._to_bytes(ExecOrderLocalID)
self.ActionLocalID=self._to_bytes(ActionLocalID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.OrderActionStatus=self._to_bytes(OrderActionStatus)
self.UserID=self._to_bytes(UserID)
self.ActionType=self._to_bytes(ActionType)
self.StatusMsg=self._to_bytes(StatusMsg)
self.InstrumentID=self._to_bytes(InstrumentID)
self.BranchID=self._to_bytes(BranchID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.ExecOrderActionRef=int(i_tuple[3])
self.ExecOrderRef=self._to_bytes(i_tuple[4])
self.RequestID=int(i_tuple[5])
self.FrontID=int(i_tuple[6])
self.SessionID=int(i_tuple[7])
self.ExchangeID=self._to_bytes(i_tuple[8])
self.ExecOrderSysID=self._to_bytes(i_tuple[9])
self.ActionFlag=self._to_bytes(i_tuple[10])
self.ActionDate=self._to_bytes(i_tuple[11])
self.ActionTime=self._to_bytes(i_tuple[12])
self.TraderID=self._to_bytes(i_tuple[13])
self.InstallID=int(i_tuple[14])
self.ExecOrderLocalID=self._to_bytes(i_tuple[15])
self.ActionLocalID=self._to_bytes(i_tuple[16])
self.ParticipantID=self._to_bytes(i_tuple[17])
self.ClientID=self._to_bytes(i_tuple[18])
self.BusinessUnit=self._to_bytes(i_tuple[19])
self.OrderActionStatus=self._to_bytes(i_tuple[20])
self.UserID=self._to_bytes(i_tuple[21])
self.ActionType=self._to_bytes(i_tuple[22])
self.StatusMsg=self._to_bytes(i_tuple[23])
self.InstrumentID=self._to_bytes(i_tuple[24])
self.BranchID=self._to_bytes(i_tuple[25])
self.InvestUnitID=self._to_bytes(i_tuple[26])
self.IPAddress=self._to_bytes(i_tuple[27])
self.MacAddress=self._to_bytes(i_tuple[28])
class QryExecOrderField(Base):
"""执行宣告查询"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ExecOrderSysID',ctypes.c_char*21)# 执行宣告编号
,('InsertTimeStart',ctypes.c_char*9)# 开始时间
,('InsertTimeEnd',ctypes.c_char*9)# 结束时间
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ExchangeID='',ExecOrderSysID='',InsertTimeStart='',InsertTimeEnd=''):
super(QryExecOrderField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ExecOrderSysID=self._to_bytes(ExecOrderSysID)
self.InsertTimeStart=self._to_bytes(InsertTimeStart)
self.InsertTimeEnd=self._to_bytes(InsertTimeEnd)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.ExecOrderSysID=self._to_bytes(i_tuple[5])
self.InsertTimeStart=self._to_bytes(i_tuple[6])
self.InsertTimeEnd=self._to_bytes(i_tuple[7])
class ExchangeExecOrderField(Base):
"""交易所执行宣告信息"""
_fields_ = [
('Volume',ctypes.c_int)# ///数量
,('RequestID',ctypes.c_int)# 请求编号
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('OffsetFlag',ctypes.c_char)# 开平标志
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('ActionType',ctypes.c_char)# 执行类型
,('PosiDirection',ctypes.c_char)# 保留头寸申请的持仓方向
,('ReservePositionFlag',ctypes.c_char)# 期权行权后是否保留期货头寸的标记,该字段已废弃
,('CloseFlag',ctypes.c_char)# 期权行权后生成的头寸是否自动平仓
,('ExecOrderLocalID',ctypes.c_char*13)# 本地执行宣告编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('OrderSubmitStatus',ctypes.c_char)# 执行宣告提交状态
,('NotifySequence',ctypes.c_int)# 报单提示序号
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('ExecOrderSysID',ctypes.c_char*21)# 执行宣告编号
,('InsertDate',ctypes.c_char*9)# 报单日期
,('InsertTime',ctypes.c_char*9)# 插入时间
,('CancelTime',ctypes.c_char*9)# 撤销时间
,('ExecResult',ctypes.c_char)# 执行结果
,('ClearingPartID',ctypes.c_char*11)# 结算会员编号
,('SequenceNo',ctypes.c_int)# 序号
,('BranchID',ctypes.c_char*9)# 营业部编号
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,Volume= 0,RequestID=0,BusinessUnit='',OffsetFlag='',HedgeFlag='',ActionType='',PosiDirection='',ReservePositionFlag='',CloseFlag='',ExecOrderLocalID='',ExchangeID='',ParticipantID='',ClientID='',ExchangeInstID='',TraderID='',InstallID=0,OrderSubmitStatus='',NotifySequence=0,TradingDay='',SettlementID=0,ExecOrderSysID='',InsertDate='',InsertTime='',CancelTime='',ExecResult='',ClearingPartID='',SequenceNo=0,BranchID='',IPAddress='',MacAddress=''):
super(ExchangeExecOrderField,self).__init__()
self.Volume=int(Volume)
self.RequestID=int(RequestID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.OffsetFlag=self._to_bytes(OffsetFlag)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.ActionType=self._to_bytes(ActionType)
self.PosiDirection=self._to_bytes(PosiDirection)
self.ReservePositionFlag=self._to_bytes(ReservePositionFlag)
self.CloseFlag=self._to_bytes(CloseFlag)
self.ExecOrderLocalID=self._to_bytes(ExecOrderLocalID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.OrderSubmitStatus=self._to_bytes(OrderSubmitStatus)
self.NotifySequence=int(NotifySequence)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.ExecOrderSysID=self._to_bytes(ExecOrderSysID)
self.InsertDate=self._to_bytes(InsertDate)
self.InsertTime=self._to_bytes(InsertTime)
self.CancelTime=self._to_bytes(CancelTime)
self.ExecResult=self._to_bytes(ExecResult)
self.ClearingPartID=self._to_bytes(ClearingPartID)
self.SequenceNo=int(SequenceNo)
self.BranchID=self._to_bytes(BranchID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.Volume=int(i_tuple[1])
self.RequestID=int(i_tuple[2])
self.BusinessUnit=self._to_bytes(i_tuple[3])
self.OffsetFlag=self._to_bytes(i_tuple[4])
self.HedgeFlag=self._to_bytes(i_tuple[5])
self.ActionType=self._to_bytes(i_tuple[6])
self.PosiDirection=self._to_bytes(i_tuple[7])
self.ReservePositionFlag=self._to_bytes(i_tuple[8])
self.CloseFlag=self._to_bytes(i_tuple[9])
self.ExecOrderLocalID=self._to_bytes(i_tuple[10])
self.ExchangeID=self._to_bytes(i_tuple[11])
self.ParticipantID=self._to_bytes(i_tuple[12])
self.ClientID=self._to_bytes(i_tuple[13])
self.ExchangeInstID=self._to_bytes(i_tuple[14])
self.TraderID=self._to_bytes(i_tuple[15])
self.InstallID=int(i_tuple[16])
self.OrderSubmitStatus=self._to_bytes(i_tuple[17])
self.NotifySequence=int(i_tuple[18])
self.TradingDay=self._to_bytes(i_tuple[19])
self.SettlementID=int(i_tuple[20])
self.ExecOrderSysID=self._to_bytes(i_tuple[21])
self.InsertDate=self._to_bytes(i_tuple[22])
self.InsertTime=self._to_bytes(i_tuple[23])
self.CancelTime=self._to_bytes(i_tuple[24])
self.ExecResult=self._to_bytes(i_tuple[25])
self.ClearingPartID=self._to_bytes(i_tuple[26])
self.SequenceNo=int(i_tuple[27])
self.BranchID=self._to_bytes(i_tuple[28])
self.IPAddress=self._to_bytes(i_tuple[29])
self.MacAddress=self._to_bytes(i_tuple[30])
class QryExchangeExecOrderField(Base):
"""交易所执行宣告查询"""
_fields_ = [
('ParticipantID',ctypes.c_char*11)# ///会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
]
def __init__(self,ParticipantID= '',ClientID='',ExchangeInstID='',ExchangeID='',TraderID=''):
super(QryExchangeExecOrderField,self).__init__()
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.TraderID=self._to_bytes(TraderID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ParticipantID=self._to_bytes(i_tuple[1])
self.ClientID=self._to_bytes(i_tuple[2])
self.ExchangeInstID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.TraderID=self._to_bytes(i_tuple[5])
class QryExecOrderActionField(Base):
"""执行宣告操作查询"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
]
def __init__(self,BrokerID= '',InvestorID='',ExchangeID=''):
super(QryExecOrderActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
class ExchangeExecOrderActionField(Base):
"""交易所执行宣告操作"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('ExecOrderSysID',ctypes.c_char*21)# 执行宣告操作编号
,('ActionFlag',ctypes.c_char)# 操作标志
,('ActionDate',ctypes.c_char*9)# 操作日期
,('ActionTime',ctypes.c_char*9)# 操作时间
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('ExecOrderLocalID',ctypes.c_char*13)# 本地执行宣告编号
,('ActionLocalID',ctypes.c_char*13)# 操作本地编号
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('OrderActionStatus',ctypes.c_char)# 报单操作状态
,('UserID',ctypes.c_char*16)# 用户代码
,('ActionType',ctypes.c_char)# 执行类型
,('BranchID',ctypes.c_char*9)# 营业部编号
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,ExchangeID= '',ExecOrderSysID='',ActionFlag='',ActionDate='',ActionTime='',TraderID='',InstallID=0,ExecOrderLocalID='',ActionLocalID='',ParticipantID='',ClientID='',BusinessUnit='',OrderActionStatus='',UserID='',ActionType='',BranchID='',IPAddress='',MacAddress=''):
super(ExchangeExecOrderActionField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.ExecOrderSysID=self._to_bytes(ExecOrderSysID)
self.ActionFlag=self._to_bytes(ActionFlag)
self.ActionDate=self._to_bytes(ActionDate)
self.ActionTime=self._to_bytes(ActionTime)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.ExecOrderLocalID=self._to_bytes(ExecOrderLocalID)
self.ActionLocalID=self._to_bytes(ActionLocalID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.OrderActionStatus=self._to_bytes(OrderActionStatus)
self.UserID=self._to_bytes(UserID)
self.ActionType=self._to_bytes(ActionType)
self.BranchID=self._to_bytes(BranchID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.ExecOrderSysID=self._to_bytes(i_tuple[2])
self.ActionFlag=self._to_bytes(i_tuple[3])
self.ActionDate=self._to_bytes(i_tuple[4])
self.ActionTime=self._to_bytes(i_tuple[5])
self.TraderID=self._to_bytes(i_tuple[6])
self.InstallID=int(i_tuple[7])
self.ExecOrderLocalID=self._to_bytes(i_tuple[8])
self.ActionLocalID=self._to_bytes(i_tuple[9])
self.ParticipantID=self._to_bytes(i_tuple[10])
self.ClientID=self._to_bytes(i_tuple[11])
self.BusinessUnit=self._to_bytes(i_tuple[12])
self.OrderActionStatus=self._to_bytes(i_tuple[13])
self.UserID=self._to_bytes(i_tuple[14])
self.ActionType=self._to_bytes(i_tuple[15])
self.BranchID=self._to_bytes(i_tuple[16])
self.IPAddress=self._to_bytes(i_tuple[17])
self.MacAddress=self._to_bytes(i_tuple[18])
class QryExchangeExecOrderActionField(Base):
"""交易所执行宣告操作查询"""
_fields_ = [
('ParticipantID',ctypes.c_char*11)# ///会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
]
def __init__(self,ParticipantID= '',ClientID='',ExchangeID='',TraderID=''):
super(QryExchangeExecOrderActionField,self).__init__()
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.TraderID=self._to_bytes(TraderID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ParticipantID=self._to_bytes(i_tuple[1])
self.ClientID=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
self.TraderID=self._to_bytes(i_tuple[4])
class ErrExecOrderField(Base):
"""错误执行宣告"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExecOrderRef',ctypes.c_char*13)# 执行宣告引用
,('UserID',ctypes.c_char*16)# 用户代码
,('Volume',ctypes.c_int)# 数量
,('RequestID',ctypes.c_int)# 请求编号
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('OffsetFlag',ctypes.c_char)# 开平标志
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('ActionType',ctypes.c_char)# 执行类型
,('PosiDirection',ctypes.c_char)# 保留头寸申请的持仓方向
,('ReservePositionFlag',ctypes.c_char)# 期权行权后是否保留期货头寸的标记,该字段已废弃
,('CloseFlag',ctypes.c_char)# 期权行权后生成的头寸是否自动平仓
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('AccountID',ctypes.c_char*13)# 资金账号
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('ClientID',ctypes.c_char*11)# 交易编码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ExecOrderRef='',UserID='',Volume=0,RequestID=0,BusinessUnit='',OffsetFlag='',HedgeFlag='',ActionType='',PosiDirection='',ReservePositionFlag='',CloseFlag='',ExchangeID='',InvestUnitID='',AccountID='',CurrencyID='',ClientID='',IPAddress='',MacAddress='',ErrorID=0,ErrorMsg=''):
super(ErrExecOrderField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExecOrderRef=self._to_bytes(ExecOrderRef)
self.UserID=self._to_bytes(UserID)
self.Volume=int(Volume)
self.RequestID=int(RequestID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.OffsetFlag=self._to_bytes(OffsetFlag)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.ActionType=self._to_bytes(ActionType)
self.PosiDirection=self._to_bytes(PosiDirection)
self.ReservePositionFlag=self._to_bytes(ReservePositionFlag)
self.CloseFlag=self._to_bytes(CloseFlag)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
self.ClientID=self._to_bytes(ClientID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ExecOrderRef=self._to_bytes(i_tuple[4])
self.UserID=self._to_bytes(i_tuple[5])
self.Volume=int(i_tuple[6])
self.RequestID=int(i_tuple[7])
self.BusinessUnit=self._to_bytes(i_tuple[8])
self.OffsetFlag=self._to_bytes(i_tuple[9])
self.HedgeFlag=self._to_bytes(i_tuple[10])
self.ActionType=self._to_bytes(i_tuple[11])
self.PosiDirection=self._to_bytes(i_tuple[12])
self.ReservePositionFlag=self._to_bytes(i_tuple[13])
self.CloseFlag=self._to_bytes(i_tuple[14])
self.ExchangeID=self._to_bytes(i_tuple[15])
self.InvestUnitID=self._to_bytes(i_tuple[16])
self.AccountID=self._to_bytes(i_tuple[17])
self.CurrencyID=self._to_bytes(i_tuple[18])
self.ClientID=self._to_bytes(i_tuple[19])
self.IPAddress=self._to_bytes(i_tuple[20])
self.MacAddress=self._to_bytes(i_tuple[21])
self.ErrorID=int(i_tuple[22])
self.ErrorMsg=self._to_bytes(i_tuple[23])
class QryErrExecOrderField(Base):
"""查询错误执行宣告"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
]
def __init__(self,BrokerID= '',InvestorID=''):
super(QryErrExecOrderField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
class ErrExecOrderActionField(Base):
"""错误执行宣告操作"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('ExecOrderActionRef',ctypes.c_int)# 执行宣告操作引用
,('ExecOrderRef',ctypes.c_char*13)# 执行宣告引用
,('RequestID',ctypes.c_int)# 请求编号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ExecOrderSysID',ctypes.c_char*21)# 执行宣告操作编号
,('ActionFlag',ctypes.c_char)# 操作标志
,('UserID',ctypes.c_char*16)# 用户代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
]
def __init__(self,BrokerID= '',InvestorID='',ExecOrderActionRef=0,ExecOrderRef='',RequestID=0,FrontID=0,SessionID=0,ExchangeID='',ExecOrderSysID='',ActionFlag='',UserID='',InstrumentID='',InvestUnitID='',IPAddress='',MacAddress='',ErrorID=0,ErrorMsg=''):
super(ErrExecOrderActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.ExecOrderActionRef=int(ExecOrderActionRef)
self.ExecOrderRef=self._to_bytes(ExecOrderRef)
self.RequestID=int(RequestID)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ExecOrderSysID=self._to_bytes(ExecOrderSysID)
self.ActionFlag=self._to_bytes(ActionFlag)
self.UserID=self._to_bytes(UserID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.ExecOrderActionRef=int(i_tuple[3])
self.ExecOrderRef=self._to_bytes(i_tuple[4])
self.RequestID=int(i_tuple[5])
self.FrontID=int(i_tuple[6])
self.SessionID=int(i_tuple[7])
self.ExchangeID=self._to_bytes(i_tuple[8])
self.ExecOrderSysID=self._to_bytes(i_tuple[9])
self.ActionFlag=self._to_bytes(i_tuple[10])
self.UserID=self._to_bytes(i_tuple[11])
self.InstrumentID=self._to_bytes(i_tuple[12])
self.InvestUnitID=self._to_bytes(i_tuple[13])
self.IPAddress=self._to_bytes(i_tuple[14])
self.MacAddress=self._to_bytes(i_tuple[15])
self.ErrorID=int(i_tuple[16])
self.ErrorMsg=self._to_bytes(i_tuple[17])
class QryErrExecOrderActionField(Base):
"""查询错误执行宣告操作"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
]
def __init__(self,BrokerID= '',InvestorID=''):
super(QryErrExecOrderActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
class OptionInstrTradingRightField(Base):
"""投资者期权合约交易权限"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('Direction',ctypes.c_char)# 买卖方向
,('TradingRight',ctypes.c_char)# 交易权限
]
def __init__(self,InstrumentID= '',InvestorRange='',BrokerID='',InvestorID='',Direction='',TradingRight=''):
super(OptionInstrTradingRightField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.Direction=self._to_bytes(Direction)
self.TradingRight=self._to_bytes(TradingRight)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.InvestorID=self._to_bytes(i_tuple[4])
self.Direction=self._to_bytes(i_tuple[5])
self.TradingRight=self._to_bytes(i_tuple[6])
class QryOptionInstrTradingRightField(Base):
"""查询期权合约交易权限"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('Direction',ctypes.c_char)# 买卖方向
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',Direction=''):
super(QryOptionInstrTradingRightField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.Direction=self._to_bytes(Direction)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.Direction=self._to_bytes(i_tuple[4])
class InputForQuoteField(Base):
"""输入的询价"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ForQuoteRef',ctypes.c_char*13)# 询价引用
,('UserID',ctypes.c_char*16)# 用户代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ForQuoteRef='',UserID='',ExchangeID='',InvestUnitID='',IPAddress='',MacAddress=''):
super(InputForQuoteField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ForQuoteRef=self._to_bytes(ForQuoteRef)
self.UserID=self._to_bytes(UserID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ForQuoteRef=self._to_bytes(i_tuple[4])
self.UserID=self._to_bytes(i_tuple[5])
self.ExchangeID=self._to_bytes(i_tuple[6])
self.InvestUnitID=self._to_bytes(i_tuple[7])
self.IPAddress=self._to_bytes(i_tuple[8])
self.MacAddress=self._to_bytes(i_tuple[9])
class ForQuoteField(Base):
"""询价"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ForQuoteRef',ctypes.c_char*13)# 询价引用
,('UserID',ctypes.c_char*16)# 用户代码
,('ForQuoteLocalID',ctypes.c_char*13)# 本地询价编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('InsertDate',ctypes.c_char*9)# 报单日期
,('InsertTime',ctypes.c_char*9)# 插入时间
,('ForQuoteStatus',ctypes.c_char)# 询价状态
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('StatusMsg',ctypes.c_char*81)# 状态信息
,('ActiveUserID',ctypes.c_char*16)# 操作用户代码
,('BrokerForQutoSeq',ctypes.c_int)# 经纪公司询价编号
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ForQuoteRef='',UserID='',ForQuoteLocalID='',ExchangeID='',ParticipantID='',ClientID='',ExchangeInstID='',TraderID='',InstallID=0,InsertDate='',InsertTime='',ForQuoteStatus='',FrontID=0,SessionID=0,StatusMsg='',ActiveUserID='',BrokerForQutoSeq=0,InvestUnitID='',IPAddress='',MacAddress=''):
super(ForQuoteField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ForQuoteRef=self._to_bytes(ForQuoteRef)
self.UserID=self._to_bytes(UserID)
self.ForQuoteLocalID=self._to_bytes(ForQuoteLocalID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.InsertDate=self._to_bytes(InsertDate)
self.InsertTime=self._to_bytes(InsertTime)
self.ForQuoteStatus=self._to_bytes(ForQuoteStatus)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.StatusMsg=self._to_bytes(StatusMsg)
self.ActiveUserID=self._to_bytes(ActiveUserID)
self.BrokerForQutoSeq=int(BrokerForQutoSeq)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ForQuoteRef=self._to_bytes(i_tuple[4])
self.UserID=self._to_bytes(i_tuple[5])
self.ForQuoteLocalID=self._to_bytes(i_tuple[6])
self.ExchangeID=self._to_bytes(i_tuple[7])
self.ParticipantID=self._to_bytes(i_tuple[8])
self.ClientID=self._to_bytes(i_tuple[9])
self.ExchangeInstID=self._to_bytes(i_tuple[10])
self.TraderID=self._to_bytes(i_tuple[11])
self.InstallID=int(i_tuple[12])
self.InsertDate=self._to_bytes(i_tuple[13])
self.InsertTime=self._to_bytes(i_tuple[14])
self.ForQuoteStatus=self._to_bytes(i_tuple[15])
self.FrontID=int(i_tuple[16])
self.SessionID=int(i_tuple[17])
self.StatusMsg=self._to_bytes(i_tuple[18])
self.ActiveUserID=self._to_bytes(i_tuple[19])
self.BrokerForQutoSeq=int(i_tuple[20])
self.InvestUnitID=self._to_bytes(i_tuple[21])
self.IPAddress=self._to_bytes(i_tuple[22])
self.MacAddress=self._to_bytes(i_tuple[23])
class QryForQuoteField(Base):
"""询价查询"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InsertTimeStart',ctypes.c_char*9)# 开始时间
,('InsertTimeEnd',ctypes.c_char*9)# 结束时间
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ExchangeID='',InsertTimeStart='',InsertTimeEnd='',InvestUnitID=''):
super(QryForQuoteField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InsertTimeStart=self._to_bytes(InsertTimeStart)
self.InsertTimeEnd=self._to_bytes(InsertTimeEnd)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.InsertTimeStart=self._to_bytes(i_tuple[5])
self.InsertTimeEnd=self._to_bytes(i_tuple[6])
self.InvestUnitID=self._to_bytes(i_tuple[7])
class ExchangeForQuoteField(Base):
"""交易所询价信息"""
_fields_ = [
('ForQuoteLocalID',ctypes.c_char*13)# ///本地询价编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('InsertDate',ctypes.c_char*9)# 报单日期
,('InsertTime',ctypes.c_char*9)# 插入时间
,('ForQuoteStatus',ctypes.c_char)# 询价状态
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,ForQuoteLocalID= '',ExchangeID='',ParticipantID='',ClientID='',ExchangeInstID='',TraderID='',InstallID=0,InsertDate='',InsertTime='',ForQuoteStatus='',IPAddress='',MacAddress=''):
super(ExchangeForQuoteField,self).__init__()
self.ForQuoteLocalID=self._to_bytes(ForQuoteLocalID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.InsertDate=self._to_bytes(InsertDate)
self.InsertTime=self._to_bytes(InsertTime)
self.ForQuoteStatus=self._to_bytes(ForQuoteStatus)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ForQuoteLocalID=self._to_bytes(i_tuple[1])
self.ExchangeID=self._to_bytes(i_tuple[2])
self.ParticipantID=self._to_bytes(i_tuple[3])
self.ClientID=self._to_bytes(i_tuple[4])
self.ExchangeInstID=self._to_bytes(i_tuple[5])
self.TraderID=self._to_bytes(i_tuple[6])
self.InstallID=int(i_tuple[7])
self.InsertDate=self._to_bytes(i_tuple[8])
self.InsertTime=self._to_bytes(i_tuple[9])
self.ForQuoteStatus=self._to_bytes(i_tuple[10])
self.IPAddress=self._to_bytes(i_tuple[11])
self.MacAddress=self._to_bytes(i_tuple[12])
class QryExchangeForQuoteField(Base):
"""交易所询价查询"""
_fields_ = [
('ParticipantID',ctypes.c_char*11)# ///会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
]
def __init__(self,ParticipantID= '',ClientID='',ExchangeInstID='',ExchangeID='',TraderID=''):
super(QryExchangeForQuoteField,self).__init__()
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.TraderID=self._to_bytes(TraderID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ParticipantID=self._to_bytes(i_tuple[1])
self.ClientID=self._to_bytes(i_tuple[2])
self.ExchangeInstID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.TraderID=self._to_bytes(i_tuple[5])
class InputQuoteField(Base):
"""输入的报价"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('QuoteRef',ctypes.c_char*13)# 报价引用
,('UserID',ctypes.c_char*16)# 用户代码
,('AskPrice',ctypes.c_double)# 卖价格
,('BidPrice',ctypes.c_double)# 买价格
,('AskVolume',ctypes.c_int)# 卖数量
,('BidVolume',ctypes.c_int)# 买数量
,('RequestID',ctypes.c_int)# 请求编号
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('AskOffsetFlag',ctypes.c_char)# 卖开平标志
,('BidOffsetFlag',ctypes.c_char)# 买开平标志
,('AskHedgeFlag',ctypes.c_char)# 卖投机套保标志
,('BidHedgeFlag',ctypes.c_char)# 买投机套保标志
,('AskOrderRef',ctypes.c_char*13)# 衍生卖报单引用
,('BidOrderRef',ctypes.c_char*13)# 衍生买报单引用
,('ForQuoteSysID',ctypes.c_char*21)# 应价编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('ClientID',ctypes.c_char*11)# 交易编码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',QuoteRef='',UserID='',AskPrice=0.0,BidPrice=0.0,AskVolume=0,BidVolume=0,RequestID=0,BusinessUnit='',AskOffsetFlag='',BidOffsetFlag='',AskHedgeFlag='',BidHedgeFlag='',AskOrderRef='',BidOrderRef='',ForQuoteSysID='',ExchangeID='',InvestUnitID='',ClientID='',IPAddress='',MacAddress=''):
super(InputQuoteField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.QuoteRef=self._to_bytes(QuoteRef)
self.UserID=self._to_bytes(UserID)
self.AskPrice=float(AskPrice)
self.BidPrice=float(BidPrice)
self.AskVolume=int(AskVolume)
self.BidVolume=int(BidVolume)
self.RequestID=int(RequestID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.AskOffsetFlag=self._to_bytes(AskOffsetFlag)
self.BidOffsetFlag=self._to_bytes(BidOffsetFlag)
self.AskHedgeFlag=self._to_bytes(AskHedgeFlag)
self.BidHedgeFlag=self._to_bytes(BidHedgeFlag)
self.AskOrderRef=self._to_bytes(AskOrderRef)
self.BidOrderRef=self._to_bytes(BidOrderRef)
self.ForQuoteSysID=self._to_bytes(ForQuoteSysID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.ClientID=self._to_bytes(ClientID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.QuoteRef=self._to_bytes(i_tuple[4])
self.UserID=self._to_bytes(i_tuple[5])
self.AskPrice=float(i_tuple[6])
self.BidPrice=float(i_tuple[7])
self.AskVolume=int(i_tuple[8])
self.BidVolume=int(i_tuple[9])
self.RequestID=int(i_tuple[10])
self.BusinessUnit=self._to_bytes(i_tuple[11])
self.AskOffsetFlag=self._to_bytes(i_tuple[12])
self.BidOffsetFlag=self._to_bytes(i_tuple[13])
self.AskHedgeFlag=self._to_bytes(i_tuple[14])
self.BidHedgeFlag=self._to_bytes(i_tuple[15])
self.AskOrderRef=self._to_bytes(i_tuple[16])
self.BidOrderRef=self._to_bytes(i_tuple[17])
self.ForQuoteSysID=self._to_bytes(i_tuple[18])
self.ExchangeID=self._to_bytes(i_tuple[19])
self.InvestUnitID=self._to_bytes(i_tuple[20])
self.ClientID=self._to_bytes(i_tuple[21])
self.IPAddress=self._to_bytes(i_tuple[22])
self.MacAddress=self._to_bytes(i_tuple[23])
class InputQuoteActionField(Base):
"""输入报价操作"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('QuoteActionRef',ctypes.c_int)# 报价操作引用
,('QuoteRef',ctypes.c_char*13)# 报价引用
,('RequestID',ctypes.c_int)# 请求编号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('QuoteSysID',ctypes.c_char*21)# 报价操作编号
,('ActionFlag',ctypes.c_char)# 操作标志
,('UserID',ctypes.c_char*16)# 用户代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('ClientID',ctypes.c_char*11)# 交易编码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',QuoteActionRef=0,QuoteRef='',RequestID=0,FrontID=0,SessionID=0,ExchangeID='',QuoteSysID='',ActionFlag='',UserID='',InstrumentID='',InvestUnitID='',ClientID='',IPAddress='',MacAddress=''):
super(InputQuoteActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.QuoteActionRef=int(QuoteActionRef)
self.QuoteRef=self._to_bytes(QuoteRef)
self.RequestID=int(RequestID)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.QuoteSysID=self._to_bytes(QuoteSysID)
self.ActionFlag=self._to_bytes(ActionFlag)
self.UserID=self._to_bytes(UserID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.ClientID=self._to_bytes(ClientID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.QuoteActionRef=int(i_tuple[3])
self.QuoteRef=self._to_bytes(i_tuple[4])
self.RequestID=int(i_tuple[5])
self.FrontID=int(i_tuple[6])
self.SessionID=int(i_tuple[7])
self.ExchangeID=self._to_bytes(i_tuple[8])
self.QuoteSysID=self._to_bytes(i_tuple[9])
self.ActionFlag=self._to_bytes(i_tuple[10])
self.UserID=self._to_bytes(i_tuple[11])
self.InstrumentID=self._to_bytes(i_tuple[12])
self.InvestUnitID=self._to_bytes(i_tuple[13])
self.ClientID=self._to_bytes(i_tuple[14])
self.IPAddress=self._to_bytes(i_tuple[15])
self.MacAddress=self._to_bytes(i_tuple[16])
class QuoteField(Base):
"""报价"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('QuoteRef',ctypes.c_char*13)# 报价引用
,('UserID',ctypes.c_char*16)# 用户代码
,('AskPrice',ctypes.c_double)# 卖价格
,('BidPrice',ctypes.c_double)# 买价格
,('AskVolume',ctypes.c_int)# 卖数量
,('BidVolume',ctypes.c_int)# 买数量
,('RequestID',ctypes.c_int)# 请求编号
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('AskOffsetFlag',ctypes.c_char)# 卖开平标志
,('BidOffsetFlag',ctypes.c_char)# 买开平标志
,('AskHedgeFlag',ctypes.c_char)# 卖投机套保标志
,('BidHedgeFlag',ctypes.c_char)# 买投机套保标志
,('QuoteLocalID',ctypes.c_char*13)# 本地报价编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('NotifySequence',ctypes.c_int)# 报价提示序号
,('OrderSubmitStatus',ctypes.c_char)# 报价提交状态
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('QuoteSysID',ctypes.c_char*21)# 报价编号
,('InsertDate',ctypes.c_char*9)# 报单日期
,('InsertTime',ctypes.c_char*9)# 插入时间
,('CancelTime',ctypes.c_char*9)# 撤销时间
,('QuoteStatus',ctypes.c_char)# 报价状态
,('ClearingPartID',ctypes.c_char*11)# 结算会员编号
,('SequenceNo',ctypes.c_int)# 序号
,('AskOrderSysID',ctypes.c_char*21)# 卖方报单编号
,('BidOrderSysID',ctypes.c_char*21)# 买方报单编号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('UserProductInfo',ctypes.c_char*11)# 用户端产品信息
,('StatusMsg',ctypes.c_char*81)# 状态信息
,('ActiveUserID',ctypes.c_char*16)# 操作用户代码
,('BrokerQuoteSeq',ctypes.c_int)# 经纪公司报价编号
,('AskOrderRef',ctypes.c_char*13)# 衍生卖报单引用
,('BidOrderRef',ctypes.c_char*13)# 衍生买报单引用
,('ForQuoteSysID',ctypes.c_char*21)# 应价编号
,('BranchID',ctypes.c_char*9)# 营业部编号
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('AccountID',ctypes.c_char*13)# 资金账号
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',QuoteRef='',UserID='',AskPrice=0.0,BidPrice=0.0,AskVolume=0,BidVolume=0,RequestID=0,BusinessUnit='',AskOffsetFlag='',BidOffsetFlag='',AskHedgeFlag='',BidHedgeFlag='',QuoteLocalID='',ExchangeID='',ParticipantID='',ClientID='',ExchangeInstID='',TraderID='',InstallID=0,NotifySequence=0,OrderSubmitStatus='',TradingDay='',SettlementID=0,QuoteSysID='',InsertDate='',InsertTime='',CancelTime='',QuoteStatus='',ClearingPartID='',SequenceNo=0,AskOrderSysID='',BidOrderSysID='',FrontID=0,SessionID=0,UserProductInfo='',StatusMsg='',ActiveUserID='',BrokerQuoteSeq=0,AskOrderRef='',BidOrderRef='',ForQuoteSysID='',BranchID='',InvestUnitID='',AccountID='',CurrencyID='',IPAddress='',MacAddress=''):
super(QuoteField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.QuoteRef=self._to_bytes(QuoteRef)
self.UserID=self._to_bytes(UserID)
self.AskPrice=float(AskPrice)
self.BidPrice=float(BidPrice)
self.AskVolume=int(AskVolume)
self.BidVolume=int(BidVolume)
self.RequestID=int(RequestID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.AskOffsetFlag=self._to_bytes(AskOffsetFlag)
self.BidOffsetFlag=self._to_bytes(BidOffsetFlag)
self.AskHedgeFlag=self._to_bytes(AskHedgeFlag)
self.BidHedgeFlag=self._to_bytes(BidHedgeFlag)
self.QuoteLocalID=self._to_bytes(QuoteLocalID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.NotifySequence=int(NotifySequence)
self.OrderSubmitStatus=self._to_bytes(OrderSubmitStatus)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.QuoteSysID=self._to_bytes(QuoteSysID)
self.InsertDate=self._to_bytes(InsertDate)
self.InsertTime=self._to_bytes(InsertTime)
self.CancelTime=self._to_bytes(CancelTime)
self.QuoteStatus=self._to_bytes(QuoteStatus)
self.ClearingPartID=self._to_bytes(ClearingPartID)
self.SequenceNo=int(SequenceNo)
self.AskOrderSysID=self._to_bytes(AskOrderSysID)
self.BidOrderSysID=self._to_bytes(BidOrderSysID)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.UserProductInfo=self._to_bytes(UserProductInfo)
self.StatusMsg=self._to_bytes(StatusMsg)
self.ActiveUserID=self._to_bytes(ActiveUserID)
self.BrokerQuoteSeq=int(BrokerQuoteSeq)
self.AskOrderRef=self._to_bytes(AskOrderRef)
self.BidOrderRef=self._to_bytes(BidOrderRef)
self.ForQuoteSysID=self._to_bytes(ForQuoteSysID)
self.BranchID=self._to_bytes(BranchID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.QuoteRef=self._to_bytes(i_tuple[4])
self.UserID=self._to_bytes(i_tuple[5])
self.AskPrice=float(i_tuple[6])
self.BidPrice=float(i_tuple[7])
self.AskVolume=int(i_tuple[8])
self.BidVolume=int(i_tuple[9])
self.RequestID=int(i_tuple[10])
self.BusinessUnit=self._to_bytes(i_tuple[11])
self.AskOffsetFlag=self._to_bytes(i_tuple[12])
self.BidOffsetFlag=self._to_bytes(i_tuple[13])
self.AskHedgeFlag=self._to_bytes(i_tuple[14])
self.BidHedgeFlag=self._to_bytes(i_tuple[15])
self.QuoteLocalID=self._to_bytes(i_tuple[16])
self.ExchangeID=self._to_bytes(i_tuple[17])
self.ParticipantID=self._to_bytes(i_tuple[18])
self.ClientID=self._to_bytes(i_tuple[19])
self.ExchangeInstID=self._to_bytes(i_tuple[20])
self.TraderID=self._to_bytes(i_tuple[21])
self.InstallID=int(i_tuple[22])
self.NotifySequence=int(i_tuple[23])
self.OrderSubmitStatus=self._to_bytes(i_tuple[24])
self.TradingDay=self._to_bytes(i_tuple[25])
self.SettlementID=int(i_tuple[26])
self.QuoteSysID=self._to_bytes(i_tuple[27])
self.InsertDate=self._to_bytes(i_tuple[28])
self.InsertTime=self._to_bytes(i_tuple[29])
self.CancelTime=self._to_bytes(i_tuple[30])
self.QuoteStatus=self._to_bytes(i_tuple[31])
self.ClearingPartID=self._to_bytes(i_tuple[32])
self.SequenceNo=int(i_tuple[33])
self.AskOrderSysID=self._to_bytes(i_tuple[34])
self.BidOrderSysID=self._to_bytes(i_tuple[35])
self.FrontID=int(i_tuple[36])
self.SessionID=int(i_tuple[37])
self.UserProductInfo=self._to_bytes(i_tuple[38])
self.StatusMsg=self._to_bytes(i_tuple[39])
self.ActiveUserID=self._to_bytes(i_tuple[40])
self.BrokerQuoteSeq=int(i_tuple[41])
self.AskOrderRef=self._to_bytes(i_tuple[42])
self.BidOrderRef=self._to_bytes(i_tuple[43])
self.ForQuoteSysID=self._to_bytes(i_tuple[44])
self.BranchID=self._to_bytes(i_tuple[45])
self.InvestUnitID=self._to_bytes(i_tuple[46])
self.AccountID=self._to_bytes(i_tuple[47])
self.CurrencyID=self._to_bytes(i_tuple[48])
self.IPAddress=self._to_bytes(i_tuple[49])
self.MacAddress=self._to_bytes(i_tuple[50])
class QuoteActionField(Base):
"""报价操作"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('QuoteActionRef',ctypes.c_int)# 报价操作引用
,('QuoteRef',ctypes.c_char*13)# 报价引用
,('RequestID',ctypes.c_int)# 请求编号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('QuoteSysID',ctypes.c_char*21)# 报价操作编号
,('ActionFlag',ctypes.c_char)# 操作标志
,('ActionDate',ctypes.c_char*9)# 操作日期
,('ActionTime',ctypes.c_char*9)# 操作时间
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('QuoteLocalID',ctypes.c_char*13)# 本地报价编号
,('ActionLocalID',ctypes.c_char*13)# 操作本地编号
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('OrderActionStatus',ctypes.c_char)# 报单操作状态
,('UserID',ctypes.c_char*16)# 用户代码
,('StatusMsg',ctypes.c_char*81)# 状态信息
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('BranchID',ctypes.c_char*9)# 营业部编号
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',QuoteActionRef=0,QuoteRef='',RequestID=0,FrontID=0,SessionID=0,ExchangeID='',QuoteSysID='',ActionFlag='',ActionDate='',ActionTime='',TraderID='',InstallID=0,QuoteLocalID='',ActionLocalID='',ParticipantID='',ClientID='',BusinessUnit='',OrderActionStatus='',UserID='',StatusMsg='',InstrumentID='',BranchID='',InvestUnitID='',IPAddress='',MacAddress=''):
super(QuoteActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.QuoteActionRef=int(QuoteActionRef)
self.QuoteRef=self._to_bytes(QuoteRef)
self.RequestID=int(RequestID)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.QuoteSysID=self._to_bytes(QuoteSysID)
self.ActionFlag=self._to_bytes(ActionFlag)
self.ActionDate=self._to_bytes(ActionDate)
self.ActionTime=self._to_bytes(ActionTime)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.QuoteLocalID=self._to_bytes(QuoteLocalID)
self.ActionLocalID=self._to_bytes(ActionLocalID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.OrderActionStatus=self._to_bytes(OrderActionStatus)
self.UserID=self._to_bytes(UserID)
self.StatusMsg=self._to_bytes(StatusMsg)
self.InstrumentID=self._to_bytes(InstrumentID)
self.BranchID=self._to_bytes(BranchID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.QuoteActionRef=int(i_tuple[3])
self.QuoteRef=self._to_bytes(i_tuple[4])
self.RequestID=int(i_tuple[5])
self.FrontID=int(i_tuple[6])
self.SessionID=int(i_tuple[7])
self.ExchangeID=self._to_bytes(i_tuple[8])
self.QuoteSysID=self._to_bytes(i_tuple[9])
self.ActionFlag=self._to_bytes(i_tuple[10])
self.ActionDate=self._to_bytes(i_tuple[11])
self.ActionTime=self._to_bytes(i_tuple[12])
self.TraderID=self._to_bytes(i_tuple[13])
self.InstallID=int(i_tuple[14])
self.QuoteLocalID=self._to_bytes(i_tuple[15])
self.ActionLocalID=self._to_bytes(i_tuple[16])
self.ParticipantID=self._to_bytes(i_tuple[17])
self.ClientID=self._to_bytes(i_tuple[18])
self.BusinessUnit=self._to_bytes(i_tuple[19])
self.OrderActionStatus=self._to_bytes(i_tuple[20])
self.UserID=self._to_bytes(i_tuple[21])
self.StatusMsg=self._to_bytes(i_tuple[22])
self.InstrumentID=self._to_bytes(i_tuple[23])
self.BranchID=self._to_bytes(i_tuple[24])
self.InvestUnitID=self._to_bytes(i_tuple[25])
self.IPAddress=self._to_bytes(i_tuple[26])
self.MacAddress=self._to_bytes(i_tuple[27])
class QryQuoteField(Base):
"""报价查询"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('QuoteSysID',ctypes.c_char*21)# 报价编号
,('InsertTimeStart',ctypes.c_char*9)# 开始时间
,('InsertTimeEnd',ctypes.c_char*9)# 结束时间
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ExchangeID='',QuoteSysID='',InsertTimeStart='',InsertTimeEnd='',InvestUnitID=''):
super(QryQuoteField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.QuoteSysID=self._to_bytes(QuoteSysID)
self.InsertTimeStart=self._to_bytes(InsertTimeStart)
self.InsertTimeEnd=self._to_bytes(InsertTimeEnd)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.QuoteSysID=self._to_bytes(i_tuple[5])
self.InsertTimeStart=self._to_bytes(i_tuple[6])
self.InsertTimeEnd=self._to_bytes(i_tuple[7])
self.InvestUnitID=self._to_bytes(i_tuple[8])
class ExchangeQuoteField(Base):
"""交易所报价信息"""
_fields_ = [
('AskPrice',ctypes.c_double)# ///卖价格
,('BidPrice',ctypes.c_double)# 买价格
,('AskVolume',ctypes.c_int)# 卖数量
,('BidVolume',ctypes.c_int)# 买数量
,('RequestID',ctypes.c_int)# 请求编号
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('AskOffsetFlag',ctypes.c_char)# 卖开平标志
,('BidOffsetFlag',ctypes.c_char)# 买开平标志
,('AskHedgeFlag',ctypes.c_char)# 卖投机套保标志
,('BidHedgeFlag',ctypes.c_char)# 买投机套保标志
,('QuoteLocalID',ctypes.c_char*13)# 本地报价编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('NotifySequence',ctypes.c_int)# 报价提示序号
,('OrderSubmitStatus',ctypes.c_char)# 报价提交状态
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('QuoteSysID',ctypes.c_char*21)# 报价编号
,('InsertDate',ctypes.c_char*9)# 报单日期
,('InsertTime',ctypes.c_char*9)# 插入时间
,('CancelTime',ctypes.c_char*9)# 撤销时间
,('QuoteStatus',ctypes.c_char)# 报价状态
,('ClearingPartID',ctypes.c_char*11)# 结算会员编号
,('SequenceNo',ctypes.c_int)# 序号
,('AskOrderSysID',ctypes.c_char*21)# 卖方报单编号
,('BidOrderSysID',ctypes.c_char*21)# 买方报单编号
,('ForQuoteSysID',ctypes.c_char*21)# 应价编号
,('BranchID',ctypes.c_char*9)# 营业部编号
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,AskPrice= 0.0,BidPrice=0.0,AskVolume=0,BidVolume=0,RequestID=0,BusinessUnit='',AskOffsetFlag='',BidOffsetFlag='',AskHedgeFlag='',BidHedgeFlag='',QuoteLocalID='',ExchangeID='',ParticipantID='',ClientID='',ExchangeInstID='',TraderID='',InstallID=0,NotifySequence=0,OrderSubmitStatus='',TradingDay='',SettlementID=0,QuoteSysID='',InsertDate='',InsertTime='',CancelTime='',QuoteStatus='',ClearingPartID='',SequenceNo=0,AskOrderSysID='',BidOrderSysID='',ForQuoteSysID='',BranchID='',IPAddress='',MacAddress=''):
super(ExchangeQuoteField,self).__init__()
self.AskPrice=float(AskPrice)
self.BidPrice=float(BidPrice)
self.AskVolume=int(AskVolume)
self.BidVolume=int(BidVolume)
self.RequestID=int(RequestID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.AskOffsetFlag=self._to_bytes(AskOffsetFlag)
self.BidOffsetFlag=self._to_bytes(BidOffsetFlag)
self.AskHedgeFlag=self._to_bytes(AskHedgeFlag)
self.BidHedgeFlag=self._to_bytes(BidHedgeFlag)
self.QuoteLocalID=self._to_bytes(QuoteLocalID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.NotifySequence=int(NotifySequence)
self.OrderSubmitStatus=self._to_bytes(OrderSubmitStatus)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.QuoteSysID=self._to_bytes(QuoteSysID)
self.InsertDate=self._to_bytes(InsertDate)
self.InsertTime=self._to_bytes(InsertTime)
self.CancelTime=self._to_bytes(CancelTime)
self.QuoteStatus=self._to_bytes(QuoteStatus)
self.ClearingPartID=self._to_bytes(ClearingPartID)
self.SequenceNo=int(SequenceNo)
self.AskOrderSysID=self._to_bytes(AskOrderSysID)
self.BidOrderSysID=self._to_bytes(BidOrderSysID)
self.ForQuoteSysID=self._to_bytes(ForQuoteSysID)
self.BranchID=self._to_bytes(BranchID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.AskPrice=float(i_tuple[1])
self.BidPrice=float(i_tuple[2])
self.AskVolume=int(i_tuple[3])
self.BidVolume=int(i_tuple[4])
self.RequestID=int(i_tuple[5])
self.BusinessUnit=self._to_bytes(i_tuple[6])
self.AskOffsetFlag=self._to_bytes(i_tuple[7])
self.BidOffsetFlag=self._to_bytes(i_tuple[8])
self.AskHedgeFlag=self._to_bytes(i_tuple[9])
self.BidHedgeFlag=self._to_bytes(i_tuple[10])
self.QuoteLocalID=self._to_bytes(i_tuple[11])
self.ExchangeID=self._to_bytes(i_tuple[12])
self.ParticipantID=self._to_bytes(i_tuple[13])
self.ClientID=self._to_bytes(i_tuple[14])
self.ExchangeInstID=self._to_bytes(i_tuple[15])
self.TraderID=self._to_bytes(i_tuple[16])
self.InstallID=int(i_tuple[17])
self.NotifySequence=int(i_tuple[18])
self.OrderSubmitStatus=self._to_bytes(i_tuple[19])
self.TradingDay=self._to_bytes(i_tuple[20])
self.SettlementID=int(i_tuple[21])
self.QuoteSysID=self._to_bytes(i_tuple[22])
self.InsertDate=self._to_bytes(i_tuple[23])
self.InsertTime=self._to_bytes(i_tuple[24])
self.CancelTime=self._to_bytes(i_tuple[25])
self.QuoteStatus=self._to_bytes(i_tuple[26])
self.ClearingPartID=self._to_bytes(i_tuple[27])
self.SequenceNo=int(i_tuple[28])
self.AskOrderSysID=self._to_bytes(i_tuple[29])
self.BidOrderSysID=self._to_bytes(i_tuple[30])
self.ForQuoteSysID=self._to_bytes(i_tuple[31])
self.BranchID=self._to_bytes(i_tuple[32])
self.IPAddress=self._to_bytes(i_tuple[33])
self.MacAddress=self._to_bytes(i_tuple[34])
class QryExchangeQuoteField(Base):
"""交易所报价查询"""
_fields_ = [
('ParticipantID',ctypes.c_char*11)# ///会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
]
def __init__(self,ParticipantID= '',ClientID='',ExchangeInstID='',ExchangeID='',TraderID=''):
super(QryExchangeQuoteField,self).__init__()
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.TraderID=self._to_bytes(TraderID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ParticipantID=self._to_bytes(i_tuple[1])
self.ClientID=self._to_bytes(i_tuple[2])
self.ExchangeInstID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.TraderID=self._to_bytes(i_tuple[5])
class QryQuoteActionField(Base):
"""报价操作查询"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
]
def __init__(self,BrokerID= '',InvestorID='',ExchangeID=''):
super(QryQuoteActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
class ExchangeQuoteActionField(Base):
"""交易所报价操作"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('QuoteSysID',ctypes.c_char*21)# 报价操作编号
,('ActionFlag',ctypes.c_char)# 操作标志
,('ActionDate',ctypes.c_char*9)# 操作日期
,('ActionTime',ctypes.c_char*9)# 操作时间
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('QuoteLocalID',ctypes.c_char*13)# 本地报价编号
,('ActionLocalID',ctypes.c_char*13)# 操作本地编号
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('OrderActionStatus',ctypes.c_char)# 报单操作状态
,('UserID',ctypes.c_char*16)# 用户代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,ExchangeID= '',QuoteSysID='',ActionFlag='',ActionDate='',ActionTime='',TraderID='',InstallID=0,QuoteLocalID='',ActionLocalID='',ParticipantID='',ClientID='',BusinessUnit='',OrderActionStatus='',UserID='',IPAddress='',MacAddress=''):
super(ExchangeQuoteActionField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.QuoteSysID=self._to_bytes(QuoteSysID)
self.ActionFlag=self._to_bytes(ActionFlag)
self.ActionDate=self._to_bytes(ActionDate)
self.ActionTime=self._to_bytes(ActionTime)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.QuoteLocalID=self._to_bytes(QuoteLocalID)
self.ActionLocalID=self._to_bytes(ActionLocalID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.OrderActionStatus=self._to_bytes(OrderActionStatus)
self.UserID=self._to_bytes(UserID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.QuoteSysID=self._to_bytes(i_tuple[2])
self.ActionFlag=self._to_bytes(i_tuple[3])
self.ActionDate=self._to_bytes(i_tuple[4])
self.ActionTime=self._to_bytes(i_tuple[5])
self.TraderID=self._to_bytes(i_tuple[6])
self.InstallID=int(i_tuple[7])
self.QuoteLocalID=self._to_bytes(i_tuple[8])
self.ActionLocalID=self._to_bytes(i_tuple[9])
self.ParticipantID=self._to_bytes(i_tuple[10])
self.ClientID=self._to_bytes(i_tuple[11])
self.BusinessUnit=self._to_bytes(i_tuple[12])
self.OrderActionStatus=self._to_bytes(i_tuple[13])
self.UserID=self._to_bytes(i_tuple[14])
self.IPAddress=self._to_bytes(i_tuple[15])
self.MacAddress=self._to_bytes(i_tuple[16])
class QryExchangeQuoteActionField(Base):
"""交易所报价操作查询"""
_fields_ = [
('ParticipantID',ctypes.c_char*11)# ///会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
]
def __init__(self,ParticipantID= '',ClientID='',ExchangeID='',TraderID=''):
super(QryExchangeQuoteActionField,self).__init__()
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.TraderID=self._to_bytes(TraderID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ParticipantID=self._to_bytes(i_tuple[1])
self.ClientID=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
self.TraderID=self._to_bytes(i_tuple[4])
class OptionInstrDeltaField(Base):
"""期权合约delta值"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('Delta',ctypes.c_double)# Delta值
]
def __init__(self,InstrumentID= '',InvestorRange='',BrokerID='',InvestorID='',Delta=0.0):
super(OptionInstrDeltaField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.Delta=float(Delta)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.InvestorID=self._to_bytes(i_tuple[4])
self.Delta=float(i_tuple[5])
class ForQuoteRspField(Base):
"""发给做市商的询价请求"""
_fields_ = [
('TradingDay',ctypes.c_char*9)# ///交易日
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ForQuoteSysID',ctypes.c_char*21)# 询价编号
,('ForQuoteTime',ctypes.c_char*9)# 询价时间
,('ActionDay',ctypes.c_char*9)# 业务日期
,('ExchangeID',ctypes.c_char*9)# 交易所代码
]
def __init__(self,TradingDay= '',InstrumentID='',ForQuoteSysID='',ForQuoteTime='',ActionDay='',ExchangeID=''):
super(ForQuoteRspField,self).__init__()
self.TradingDay=self._to_bytes(TradingDay)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ForQuoteSysID=self._to_bytes(ForQuoteSysID)
self.ForQuoteTime=self._to_bytes(ForQuoteTime)
self.ActionDay=self._to_bytes(ActionDay)
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradingDay=self._to_bytes(i_tuple[1])
self.InstrumentID=self._to_bytes(i_tuple[2])
self.ForQuoteSysID=self._to_bytes(i_tuple[3])
self.ForQuoteTime=self._to_bytes(i_tuple[4])
self.ActionDay=self._to_bytes(i_tuple[5])
self.ExchangeID=self._to_bytes(i_tuple[6])
class StrikeOffsetField(Base):
"""当前期权合约执行偏移值的详细内容"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('Offset',ctypes.c_double)# 执行偏移值
,('OffsetType',ctypes.c_char)# 执行偏移类型
]
def __init__(self,InstrumentID= '',InvestorRange='',BrokerID='',InvestorID='',Offset=0.0,OffsetType=''):
super(StrikeOffsetField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.Offset=float(Offset)
self.OffsetType=self._to_bytes(OffsetType)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.InvestorID=self._to_bytes(i_tuple[4])
self.Offset=float(i_tuple[5])
self.OffsetType=self._to_bytes(i_tuple[6])
class QryStrikeOffsetField(Base):
"""期权执行偏移值查询"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID=''):
super(QryStrikeOffsetField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
class InputBatchOrderActionField(Base):
"""输入批量报单操作"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('OrderActionRef',ctypes.c_int)# 报单操作引用
,('RequestID',ctypes.c_int)# 请求编号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('UserID',ctypes.c_char*16)# 用户代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',OrderActionRef=0,RequestID=0,FrontID=0,SessionID=0,ExchangeID='',UserID='',InvestUnitID='',IPAddress='',MacAddress=''):
super(InputBatchOrderActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.OrderActionRef=int(OrderActionRef)
self.RequestID=int(RequestID)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.UserID=self._to_bytes(UserID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.OrderActionRef=int(i_tuple[3])
self.RequestID=int(i_tuple[4])
self.FrontID=int(i_tuple[5])
self.SessionID=int(i_tuple[6])
self.ExchangeID=self._to_bytes(i_tuple[7])
self.UserID=self._to_bytes(i_tuple[8])
self.InvestUnitID=self._to_bytes(i_tuple[9])
self.IPAddress=self._to_bytes(i_tuple[10])
self.MacAddress=self._to_bytes(i_tuple[11])
class BatchOrderActionField(Base):
"""批量报单操作"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('OrderActionRef',ctypes.c_int)# 报单操作引用
,('RequestID',ctypes.c_int)# 请求编号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ActionDate',ctypes.c_char*9)# 操作日期
,('ActionTime',ctypes.c_char*9)# 操作时间
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('ActionLocalID',ctypes.c_char*13)# 操作本地编号
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('OrderActionStatus',ctypes.c_char)# 报单操作状态
,('UserID',ctypes.c_char*16)# 用户代码
,('StatusMsg',ctypes.c_char*81)# 状态信息
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',OrderActionRef=0,RequestID=0,FrontID=0,SessionID=0,ExchangeID='',ActionDate='',ActionTime='',TraderID='',InstallID=0,ActionLocalID='',ParticipantID='',ClientID='',BusinessUnit='',OrderActionStatus='',UserID='',StatusMsg='',InvestUnitID='',IPAddress='',MacAddress=''):
super(BatchOrderActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.OrderActionRef=int(OrderActionRef)
self.RequestID=int(RequestID)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ActionDate=self._to_bytes(ActionDate)
self.ActionTime=self._to_bytes(ActionTime)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.ActionLocalID=self._to_bytes(ActionLocalID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.OrderActionStatus=self._to_bytes(OrderActionStatus)
self.UserID=self._to_bytes(UserID)
self.StatusMsg=self._to_bytes(StatusMsg)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.OrderActionRef=int(i_tuple[3])
self.RequestID=int(i_tuple[4])
self.FrontID=int(i_tuple[5])
self.SessionID=int(i_tuple[6])
self.ExchangeID=self._to_bytes(i_tuple[7])
self.ActionDate=self._to_bytes(i_tuple[8])
self.ActionTime=self._to_bytes(i_tuple[9])
self.TraderID=self._to_bytes(i_tuple[10])
self.InstallID=int(i_tuple[11])
self.ActionLocalID=self._to_bytes(i_tuple[12])
self.ParticipantID=self._to_bytes(i_tuple[13])
self.ClientID=self._to_bytes(i_tuple[14])
self.BusinessUnit=self._to_bytes(i_tuple[15])
self.OrderActionStatus=self._to_bytes(i_tuple[16])
self.UserID=self._to_bytes(i_tuple[17])
self.StatusMsg=self._to_bytes(i_tuple[18])
self.InvestUnitID=self._to_bytes(i_tuple[19])
self.IPAddress=self._to_bytes(i_tuple[20])
self.MacAddress=self._to_bytes(i_tuple[21])
class ExchangeBatchOrderActionField(Base):
"""交易所批量报单操作"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('ActionDate',ctypes.c_char*9)# 操作日期
,('ActionTime',ctypes.c_char*9)# 操作时间
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('ActionLocalID',ctypes.c_char*13)# 操作本地编号
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('OrderActionStatus',ctypes.c_char)# 报单操作状态
,('UserID',ctypes.c_char*16)# 用户代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,ExchangeID= '',ActionDate='',ActionTime='',TraderID='',InstallID=0,ActionLocalID='',ParticipantID='',ClientID='',BusinessUnit='',OrderActionStatus='',UserID='',IPAddress='',MacAddress=''):
super(ExchangeBatchOrderActionField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.ActionDate=self._to_bytes(ActionDate)
self.ActionTime=self._to_bytes(ActionTime)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.ActionLocalID=self._to_bytes(ActionLocalID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.OrderActionStatus=self._to_bytes(OrderActionStatus)
self.UserID=self._to_bytes(UserID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.ActionDate=self._to_bytes(i_tuple[2])
self.ActionTime=self._to_bytes(i_tuple[3])
self.TraderID=self._to_bytes(i_tuple[4])
self.InstallID=int(i_tuple[5])
self.ActionLocalID=self._to_bytes(i_tuple[6])
self.ParticipantID=self._to_bytes(i_tuple[7])
self.ClientID=self._to_bytes(i_tuple[8])
self.BusinessUnit=self._to_bytes(i_tuple[9])
self.OrderActionStatus=self._to_bytes(i_tuple[10])
self.UserID=self._to_bytes(i_tuple[11])
self.IPAddress=self._to_bytes(i_tuple[12])
self.MacAddress=self._to_bytes(i_tuple[13])
class QryBatchOrderActionField(Base):
"""查询批量报单操作"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
]
def __init__(self,BrokerID= '',InvestorID='',ExchangeID=''):
super(QryBatchOrderActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
class CombInstrumentGuardField(Base):
"""组合合约安全系数"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('GuarantRatio',ctypes.c_double)#
,('ExchangeID',ctypes.c_char*9)# 交易所代码
]
def __init__(self,BrokerID= '',InstrumentID='',GuarantRatio=0.0,ExchangeID=''):
super(CombInstrumentGuardField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.GuarantRatio=float(GuarantRatio)
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InstrumentID=self._to_bytes(i_tuple[2])
self.GuarantRatio=float(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
class QryCombInstrumentGuardField(Base):
"""组合合约安全系数查询"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
]
def __init__(self,BrokerID= '',InstrumentID='',ExchangeID=''):
super(QryCombInstrumentGuardField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InstrumentID=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
class InputCombActionField(Base):
"""输入的申请组合"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('CombActionRef',ctypes.c_char*13)# 组合引用
,('UserID',ctypes.c_char*16)# 用户代码
,('Direction',ctypes.c_char)# 买卖方向
,('Volume',ctypes.c_int)# 数量
,('CombDirection',ctypes.c_char)# 组合指令方向
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',CombActionRef='',UserID='',Direction='',Volume=0,CombDirection='',HedgeFlag='',ExchangeID='',IPAddress='',MacAddress='',InvestUnitID=''):
super(InputCombActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.CombActionRef=self._to_bytes(CombActionRef)
self.UserID=self._to_bytes(UserID)
self.Direction=self._to_bytes(Direction)
self.Volume=int(Volume)
self.CombDirection=self._to_bytes(CombDirection)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.ExchangeID=self._to_bytes(ExchangeID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.CombActionRef=self._to_bytes(i_tuple[4])
self.UserID=self._to_bytes(i_tuple[5])
self.Direction=self._to_bytes(i_tuple[6])
self.Volume=int(i_tuple[7])
self.CombDirection=self._to_bytes(i_tuple[8])
self.HedgeFlag=self._to_bytes(i_tuple[9])
self.ExchangeID=self._to_bytes(i_tuple[10])
self.IPAddress=self._to_bytes(i_tuple[11])
self.MacAddress=self._to_bytes(i_tuple[12])
self.InvestUnitID=self._to_bytes(i_tuple[13])
class CombActionField(Base):
"""申请组合"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('CombActionRef',ctypes.c_char*13)# 组合引用
,('UserID',ctypes.c_char*16)# 用户代码
,('Direction',ctypes.c_char)# 买卖方向
,('Volume',ctypes.c_int)# 数量
,('CombDirection',ctypes.c_char)# 组合指令方向
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('ActionLocalID',ctypes.c_char*13)# 本地申请组合编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('ActionStatus',ctypes.c_char)# 组合状态
,('NotifySequence',ctypes.c_int)# 报单提示序号
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('SequenceNo',ctypes.c_int)# 序号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('UserProductInfo',ctypes.c_char*11)# 用户端产品信息
,('StatusMsg',ctypes.c_char*81)# 状态信息
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
,('ComTradeID',ctypes.c_char*21)# 组合编号
,('BranchID',ctypes.c_char*9)# 营业部编号
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',CombActionRef='',UserID='',Direction='',Volume=0,CombDirection='',HedgeFlag='',ActionLocalID='',ExchangeID='',ParticipantID='',ClientID='',ExchangeInstID='',TraderID='',InstallID=0,ActionStatus='',NotifySequence=0,TradingDay='',SettlementID=0,SequenceNo=0,FrontID=0,SessionID=0,UserProductInfo='',StatusMsg='',IPAddress='',MacAddress='',ComTradeID='',BranchID='',InvestUnitID=''):
super(CombActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.CombActionRef=self._to_bytes(CombActionRef)
self.UserID=self._to_bytes(UserID)
self.Direction=self._to_bytes(Direction)
self.Volume=int(Volume)
self.CombDirection=self._to_bytes(CombDirection)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.ActionLocalID=self._to_bytes(ActionLocalID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.ActionStatus=self._to_bytes(ActionStatus)
self.NotifySequence=int(NotifySequence)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.SequenceNo=int(SequenceNo)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.UserProductInfo=self._to_bytes(UserProductInfo)
self.StatusMsg=self._to_bytes(StatusMsg)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
self.ComTradeID=self._to_bytes(ComTradeID)
self.BranchID=self._to_bytes(BranchID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.CombActionRef=self._to_bytes(i_tuple[4])
self.UserID=self._to_bytes(i_tuple[5])
self.Direction=self._to_bytes(i_tuple[6])
self.Volume=int(i_tuple[7])
self.CombDirection=self._to_bytes(i_tuple[8])
self.HedgeFlag=self._to_bytes(i_tuple[9])
self.ActionLocalID=self._to_bytes(i_tuple[10])
self.ExchangeID=self._to_bytes(i_tuple[11])
self.ParticipantID=self._to_bytes(i_tuple[12])
self.ClientID=self._to_bytes(i_tuple[13])
self.ExchangeInstID=self._to_bytes(i_tuple[14])
self.TraderID=self._to_bytes(i_tuple[15])
self.InstallID=int(i_tuple[16])
self.ActionStatus=self._to_bytes(i_tuple[17])
self.NotifySequence=int(i_tuple[18])
self.TradingDay=self._to_bytes(i_tuple[19])
self.SettlementID=int(i_tuple[20])
self.SequenceNo=int(i_tuple[21])
self.FrontID=int(i_tuple[22])
self.SessionID=int(i_tuple[23])
self.UserProductInfo=self._to_bytes(i_tuple[24])
self.StatusMsg=self._to_bytes(i_tuple[25])
self.IPAddress=self._to_bytes(i_tuple[26])
self.MacAddress=self._to_bytes(i_tuple[27])
self.ComTradeID=self._to_bytes(i_tuple[28])
self.BranchID=self._to_bytes(i_tuple[29])
self.InvestUnitID=self._to_bytes(i_tuple[30])
class QryCombActionField(Base):
"""申请组合查询"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ExchangeID='',InvestUnitID=''):
super(QryCombActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.InvestUnitID=self._to_bytes(i_tuple[5])
class ExchangeCombActionField(Base):
"""交易所申请组合信息"""
_fields_ = [
('Direction',ctypes.c_char)# ///买卖方向
,('Volume',ctypes.c_int)# 数量
,('CombDirection',ctypes.c_char)# 组合指令方向
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('ActionLocalID',ctypes.c_char*13)# 本地申请组合编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('ActionStatus',ctypes.c_char)# 组合状态
,('NotifySequence',ctypes.c_int)# 报单提示序号
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('SequenceNo',ctypes.c_int)# 序号
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
,('ComTradeID',ctypes.c_char*21)# 组合编号
,('BranchID',ctypes.c_char*9)# 营业部编号
]
def __init__(self,Direction= '',Volume=0,CombDirection='',HedgeFlag='',ActionLocalID='',ExchangeID='',ParticipantID='',ClientID='',ExchangeInstID='',TraderID='',InstallID=0,ActionStatus='',NotifySequence=0,TradingDay='',SettlementID=0,SequenceNo=0,IPAddress='',MacAddress='',ComTradeID='',BranchID=''):
super(ExchangeCombActionField,self).__init__()
self.Direction=self._to_bytes(Direction)
self.Volume=int(Volume)
self.CombDirection=self._to_bytes(CombDirection)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.ActionLocalID=self._to_bytes(ActionLocalID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.ActionStatus=self._to_bytes(ActionStatus)
self.NotifySequence=int(NotifySequence)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.SequenceNo=int(SequenceNo)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
self.ComTradeID=self._to_bytes(ComTradeID)
self.BranchID=self._to_bytes(BranchID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.Direction=self._to_bytes(i_tuple[1])
self.Volume=int(i_tuple[2])
self.CombDirection=self._to_bytes(i_tuple[3])
self.HedgeFlag=self._to_bytes(i_tuple[4])
self.ActionLocalID=self._to_bytes(i_tuple[5])
self.ExchangeID=self._to_bytes(i_tuple[6])
self.ParticipantID=self._to_bytes(i_tuple[7])
self.ClientID=self._to_bytes(i_tuple[8])
self.ExchangeInstID=self._to_bytes(i_tuple[9])
self.TraderID=self._to_bytes(i_tuple[10])
self.InstallID=int(i_tuple[11])
self.ActionStatus=self._to_bytes(i_tuple[12])
self.NotifySequence=int(i_tuple[13])
self.TradingDay=self._to_bytes(i_tuple[14])
self.SettlementID=int(i_tuple[15])
self.SequenceNo=int(i_tuple[16])
self.IPAddress=self._to_bytes(i_tuple[17])
self.MacAddress=self._to_bytes(i_tuple[18])
self.ComTradeID=self._to_bytes(i_tuple[19])
self.BranchID=self._to_bytes(i_tuple[20])
class QryExchangeCombActionField(Base):
"""交易所申请组合查询"""
_fields_ = [
('ParticipantID',ctypes.c_char*11)# ///会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
]
def __init__(self,ParticipantID= '',ClientID='',ExchangeInstID='',ExchangeID='',TraderID=''):
super(QryExchangeCombActionField,self).__init__()
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.TraderID=self._to_bytes(TraderID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ParticipantID=self._to_bytes(i_tuple[1])
self.ClientID=self._to_bytes(i_tuple[2])
self.ExchangeInstID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.TraderID=self._to_bytes(i_tuple[5])
class ProductExchRateField(Base):
"""产品报价汇率"""
_fields_ = [
('ProductID',ctypes.c_char*31)# ///产品代码
,('QuoteCurrencyID',ctypes.c_char*4)# 报价币种类型
,('ExchangeRate',ctypes.c_double)# 汇率
,('ExchangeID',ctypes.c_char*9)# 交易所代码
]
def __init__(self,ProductID= '',QuoteCurrencyID='',ExchangeRate=0.0,ExchangeID=''):
super(ProductExchRateField,self).__init__()
self.ProductID=self._to_bytes(ProductID)
self.QuoteCurrencyID=self._to_bytes(QuoteCurrencyID)
self.ExchangeRate=float(ExchangeRate)
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ProductID=self._to_bytes(i_tuple[1])
self.QuoteCurrencyID=self._to_bytes(i_tuple[2])
self.ExchangeRate=float(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
class QryProductExchRateField(Base):
"""产品报价汇率查询"""
_fields_ = [
('ProductID',ctypes.c_char*31)# ///产品代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
]
def __init__(self,ProductID= '',ExchangeID=''):
super(QryProductExchRateField,self).__init__()
self.ProductID=self._to_bytes(ProductID)
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ProductID=self._to_bytes(i_tuple[1])
self.ExchangeID=self._to_bytes(i_tuple[2])
class QryForQuoteParamField(Base):
"""查询询价价差参数"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
]
def __init__(self,BrokerID= '',InstrumentID='',ExchangeID=''):
super(QryForQuoteParamField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InstrumentID=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
class ForQuoteParamField(Base):
"""询价价差参数"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('LastPrice',ctypes.c_double)# 最新价
,('PriceInterval',ctypes.c_double)# 价差
]
def __init__(self,BrokerID= '',InstrumentID='',ExchangeID='',LastPrice=0.0,PriceInterval=0.0):
super(ForQuoteParamField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.LastPrice=float(LastPrice)
self.PriceInterval=float(PriceInterval)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InstrumentID=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
self.LastPrice=float(i_tuple[4])
self.PriceInterval=float(i_tuple[5])
class MMOptionInstrCommRateField(Base):
"""当前做市商期权合约手续费的详细内容"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('OpenRatioByMoney',ctypes.c_double)# 开仓手续费率
,('OpenRatioByVolume',ctypes.c_double)# 开仓手续费
,('CloseRatioByMoney',ctypes.c_double)# 平仓手续费率
,('CloseRatioByVolume',ctypes.c_double)# 平仓手续费
,('CloseTodayRatioByMoney',ctypes.c_double)# 平今手续费率
,('CloseTodayRatioByVolume',ctypes.c_double)# 平今手续费
,('StrikeRatioByMoney',ctypes.c_double)# 执行手续费率
,('StrikeRatioByVolume',ctypes.c_double)# 执行手续费
]
def __init__(self,InstrumentID= '',InvestorRange='',BrokerID='',InvestorID='',OpenRatioByMoney=0.0,OpenRatioByVolume=0.0,CloseRatioByMoney=0.0,CloseRatioByVolume=0.0,CloseTodayRatioByMoney=0.0,CloseTodayRatioByVolume=0.0,StrikeRatioByMoney=0.0,StrikeRatioByVolume=0.0):
super(MMOptionInstrCommRateField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.OpenRatioByMoney=float(OpenRatioByMoney)
self.OpenRatioByVolume=float(OpenRatioByVolume)
self.CloseRatioByMoney=float(CloseRatioByMoney)
self.CloseRatioByVolume=float(CloseRatioByVolume)
self.CloseTodayRatioByMoney=float(CloseTodayRatioByMoney)
self.CloseTodayRatioByVolume=float(CloseTodayRatioByVolume)
self.StrikeRatioByMoney=float(StrikeRatioByMoney)
self.StrikeRatioByVolume=float(StrikeRatioByVolume)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.InvestorID=self._to_bytes(i_tuple[4])
self.OpenRatioByMoney=float(i_tuple[5])
self.OpenRatioByVolume=float(i_tuple[6])
self.CloseRatioByMoney=float(i_tuple[7])
self.CloseRatioByVolume=float(i_tuple[8])
self.CloseTodayRatioByMoney=float(i_tuple[9])
self.CloseTodayRatioByVolume=float(i_tuple[10])
self.StrikeRatioByMoney=float(i_tuple[11])
self.StrikeRatioByVolume=float(i_tuple[12])
class QryMMOptionInstrCommRateField(Base):
"""做市商期权手续费率查询"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID=''):
super(QryMMOptionInstrCommRateField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
class MMInstrumentCommissionRateField(Base):
"""做市商合约手续费率"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('OpenRatioByMoney',ctypes.c_double)# 开仓手续费率
,('OpenRatioByVolume',ctypes.c_double)# 开仓手续费
,('CloseRatioByMoney',ctypes.c_double)# 平仓手续费率
,('CloseRatioByVolume',ctypes.c_double)# 平仓手续费
,('CloseTodayRatioByMoney',ctypes.c_double)# 平今手续费率
,('CloseTodayRatioByVolume',ctypes.c_double)# 平今手续费
]
def __init__(self,InstrumentID= '',InvestorRange='',BrokerID='',InvestorID='',OpenRatioByMoney=0.0,OpenRatioByVolume=0.0,CloseRatioByMoney=0.0,CloseRatioByVolume=0.0,CloseTodayRatioByMoney=0.0,CloseTodayRatioByVolume=0.0):
super(MMInstrumentCommissionRateField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.OpenRatioByMoney=float(OpenRatioByMoney)
self.OpenRatioByVolume=float(OpenRatioByVolume)
self.CloseRatioByMoney=float(CloseRatioByMoney)
self.CloseRatioByVolume=float(CloseRatioByVolume)
self.CloseTodayRatioByMoney=float(CloseTodayRatioByMoney)
self.CloseTodayRatioByVolume=float(CloseTodayRatioByVolume)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.InvestorID=self._to_bytes(i_tuple[4])
self.OpenRatioByMoney=float(i_tuple[5])
self.OpenRatioByVolume=float(i_tuple[6])
self.CloseRatioByMoney=float(i_tuple[7])
self.CloseRatioByVolume=float(i_tuple[8])
self.CloseTodayRatioByMoney=float(i_tuple[9])
self.CloseTodayRatioByVolume=float(i_tuple[10])
class QryMMInstrumentCommissionRateField(Base):
"""查询做市商合约手续费率"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID=''):
super(QryMMInstrumentCommissionRateField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
class InstrumentOrderCommRateField(Base):
"""当前报单手续费的详细内容"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('OrderCommByVolume',ctypes.c_double)# 报单手续费
,('OrderActionCommByVolume',ctypes.c_double)# 撤单手续费
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,InstrumentID= '',InvestorRange='',BrokerID='',InvestorID='',HedgeFlag='',OrderCommByVolume=0.0,OrderActionCommByVolume=0.0,ExchangeID='',InvestUnitID=''):
super(InstrumentOrderCommRateField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.OrderCommByVolume=float(OrderCommByVolume)
self.OrderActionCommByVolume=float(OrderActionCommByVolume)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.InvestorID=self._to_bytes(i_tuple[4])
self.HedgeFlag=self._to_bytes(i_tuple[5])
self.OrderCommByVolume=float(i_tuple[6])
self.OrderActionCommByVolume=float(i_tuple[7])
self.ExchangeID=self._to_bytes(i_tuple[8])
self.InvestUnitID=self._to_bytes(i_tuple[9])
class QryInstrumentOrderCommRateField(Base):
"""报单手续费率查询"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID=''):
super(QryInstrumentOrderCommRateField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
class TradeParamField(Base):
"""交易参数"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('TradeParamID',ctypes.c_char)# 参数代码
,('TradeParamValue',ctypes.c_char*256)# 参数代码值
,('Memo',ctypes.c_char*161)# 备注
]
def __init__(self,BrokerID= '',TradeParamID='',TradeParamValue='',Memo=''):
super(TradeParamField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.TradeParamID=self._to_bytes(TradeParamID)
self.TradeParamValue=self._to_bytes(TradeParamValue)
self.Memo=self._to_bytes(Memo)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.TradeParamID=self._to_bytes(i_tuple[2])
self.TradeParamValue=self._to_bytes(i_tuple[3])
self.Memo=self._to_bytes(i_tuple[4])
class InstrumentMarginRateULField(Base):
"""合约保证金率调整"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('LongMarginRatioByMoney',ctypes.c_double)# 多头保证金率
,('LongMarginRatioByVolume',ctypes.c_double)# 多头保证金费
,('ShortMarginRatioByMoney',ctypes.c_double)# 空头保证金率
,('ShortMarginRatioByVolume',ctypes.c_double)# 空头保证金费
]
def __init__(self,InstrumentID= '',InvestorRange='',BrokerID='',InvestorID='',HedgeFlag='',LongMarginRatioByMoney=0.0,LongMarginRatioByVolume=0.0,ShortMarginRatioByMoney=0.0,ShortMarginRatioByVolume=0.0):
super(InstrumentMarginRateULField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.LongMarginRatioByMoney=float(LongMarginRatioByMoney)
self.LongMarginRatioByVolume=float(LongMarginRatioByVolume)
self.ShortMarginRatioByMoney=float(ShortMarginRatioByMoney)
self.ShortMarginRatioByVolume=float(ShortMarginRatioByVolume)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.BrokerID=self._to_bytes(i_tuple[3])
self.InvestorID=self._to_bytes(i_tuple[4])
self.HedgeFlag=self._to_bytes(i_tuple[5])
self.LongMarginRatioByMoney=float(i_tuple[6])
self.LongMarginRatioByVolume=float(i_tuple[7])
self.ShortMarginRatioByMoney=float(i_tuple[8])
self.ShortMarginRatioByVolume=float(i_tuple[9])
class FutureLimitPosiParamField(Base):
"""期货持仓限制参数"""
_fields_ = [
('InvestorRange',ctypes.c_char)# ///投资者范围
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('ProductID',ctypes.c_char*31)# 产品代码
,('SpecOpenVolume',ctypes.c_int)# 当日投机开仓数量限制
,('ArbiOpenVolume',ctypes.c_int)# 当日套利开仓数量限制
,('OpenVolume',ctypes.c_int)# 当日投机+套利开仓数量限制
]
def __init__(self,InvestorRange= '',BrokerID='',InvestorID='',ProductID='',SpecOpenVolume=0,ArbiOpenVolume=0,OpenVolume=0):
super(FutureLimitPosiParamField,self).__init__()
self.InvestorRange=self._to_bytes(InvestorRange)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.ProductID=self._to_bytes(ProductID)
self.SpecOpenVolume=int(SpecOpenVolume)
self.ArbiOpenVolume=int(ArbiOpenVolume)
self.OpenVolume=int(OpenVolume)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InvestorRange=self._to_bytes(i_tuple[1])
self.BrokerID=self._to_bytes(i_tuple[2])
self.InvestorID=self._to_bytes(i_tuple[3])
self.ProductID=self._to_bytes(i_tuple[4])
self.SpecOpenVolume=int(i_tuple[5])
self.ArbiOpenVolume=int(i_tuple[6])
self.OpenVolume=int(i_tuple[7])
class LoginForbiddenIPField(Base):
"""禁止登录IP"""
_fields_ = [
('IPAddress',ctypes.c_char*16)# ///IP地址
]
def __init__(self,IPAddress= ''):
super(LoginForbiddenIPField,self).__init__()
self.IPAddress=self._to_bytes(IPAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.IPAddress=self._to_bytes(i_tuple[1])
class IPListField(Base):
"""IP列表"""
_fields_ = [
('IPAddress',ctypes.c_char*16)# ///IP地址
,('IsWhite',ctypes.c_int)# 是否白名单
]
def __init__(self,IPAddress= '',IsWhite=0):
super(IPListField,self).__init__()
self.IPAddress=self._to_bytes(IPAddress)
self.IsWhite=int(IsWhite)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.IPAddress=self._to_bytes(i_tuple[1])
self.IsWhite=int(i_tuple[2])
class InputOptionSelfCloseField(Base):
"""输入的期权自对冲"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('OptionSelfCloseRef',ctypes.c_char*13)# 期权自对冲引用
,('UserID',ctypes.c_char*16)# 用户代码
,('Volume',ctypes.c_int)# 数量
,('RequestID',ctypes.c_int)# 请求编号
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('OptSelfCloseFlag',ctypes.c_char)# 期权行权的头寸是否自对冲
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('AccountID',ctypes.c_char*13)# 资金账号
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('ClientID',ctypes.c_char*11)# 交易编码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',OptionSelfCloseRef='',UserID='',Volume=0,RequestID=0,BusinessUnit='',HedgeFlag='',OptSelfCloseFlag='',ExchangeID='',InvestUnitID='',AccountID='',CurrencyID='',ClientID='',IPAddress='',MacAddress=''):
super(InputOptionSelfCloseField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.OptionSelfCloseRef=self._to_bytes(OptionSelfCloseRef)
self.UserID=self._to_bytes(UserID)
self.Volume=int(Volume)
self.RequestID=int(RequestID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.OptSelfCloseFlag=self._to_bytes(OptSelfCloseFlag)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
self.ClientID=self._to_bytes(ClientID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.OptionSelfCloseRef=self._to_bytes(i_tuple[4])
self.UserID=self._to_bytes(i_tuple[5])
self.Volume=int(i_tuple[6])
self.RequestID=int(i_tuple[7])
self.BusinessUnit=self._to_bytes(i_tuple[8])
self.HedgeFlag=self._to_bytes(i_tuple[9])
self.OptSelfCloseFlag=self._to_bytes(i_tuple[10])
self.ExchangeID=self._to_bytes(i_tuple[11])
self.InvestUnitID=self._to_bytes(i_tuple[12])
self.AccountID=self._to_bytes(i_tuple[13])
self.CurrencyID=self._to_bytes(i_tuple[14])
self.ClientID=self._to_bytes(i_tuple[15])
self.IPAddress=self._to_bytes(i_tuple[16])
self.MacAddress=self._to_bytes(i_tuple[17])
class InputOptionSelfCloseActionField(Base):
"""输入期权自对冲操作"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('OptionSelfCloseActionRef',ctypes.c_int)# 期权自对冲操作引用
,('OptionSelfCloseRef',ctypes.c_char*13)# 期权自对冲引用
,('RequestID',ctypes.c_int)# 请求编号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('OptionSelfCloseSysID',ctypes.c_char*21)# 期权自对冲操作编号
,('ActionFlag',ctypes.c_char)# 操作标志
,('UserID',ctypes.c_char*16)# 用户代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',OptionSelfCloseActionRef=0,OptionSelfCloseRef='',RequestID=0,FrontID=0,SessionID=0,ExchangeID='',OptionSelfCloseSysID='',ActionFlag='',UserID='',InstrumentID='',InvestUnitID='',IPAddress='',MacAddress=''):
super(InputOptionSelfCloseActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.OptionSelfCloseActionRef=int(OptionSelfCloseActionRef)
self.OptionSelfCloseRef=self._to_bytes(OptionSelfCloseRef)
self.RequestID=int(RequestID)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.OptionSelfCloseSysID=self._to_bytes(OptionSelfCloseSysID)
self.ActionFlag=self._to_bytes(ActionFlag)
self.UserID=self._to_bytes(UserID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.OptionSelfCloseActionRef=int(i_tuple[3])
self.OptionSelfCloseRef=self._to_bytes(i_tuple[4])
self.RequestID=int(i_tuple[5])
self.FrontID=int(i_tuple[6])
self.SessionID=int(i_tuple[7])
self.ExchangeID=self._to_bytes(i_tuple[8])
self.OptionSelfCloseSysID=self._to_bytes(i_tuple[9])
self.ActionFlag=self._to_bytes(i_tuple[10])
self.UserID=self._to_bytes(i_tuple[11])
self.InstrumentID=self._to_bytes(i_tuple[12])
self.InvestUnitID=self._to_bytes(i_tuple[13])
self.IPAddress=self._to_bytes(i_tuple[14])
self.MacAddress=self._to_bytes(i_tuple[15])
class OptionSelfCloseField(Base):
"""期权自对冲"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('OptionSelfCloseRef',ctypes.c_char*13)# 期权自对冲引用
,('UserID',ctypes.c_char*16)# 用户代码
,('Volume',ctypes.c_int)# 数量
,('RequestID',ctypes.c_int)# 请求编号
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('OptSelfCloseFlag',ctypes.c_char)# 期权行权的头寸是否自对冲
,('OptionSelfCloseLocalID',ctypes.c_char*13)# 本地期权自对冲编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('OrderSubmitStatus',ctypes.c_char)# 期权自对冲提交状态
,('NotifySequence',ctypes.c_int)# 报单提示序号
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('OptionSelfCloseSysID',ctypes.c_char*21)# 期权自对冲编号
,('InsertDate',ctypes.c_char*9)# 报单日期
,('InsertTime',ctypes.c_char*9)# 插入时间
,('CancelTime',ctypes.c_char*9)# 撤销时间
,('ExecResult',ctypes.c_char)# 自对冲结果
,('ClearingPartID',ctypes.c_char*11)# 结算会员编号
,('SequenceNo',ctypes.c_int)# 序号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('UserProductInfo',ctypes.c_char*11)# 用户端产品信息
,('StatusMsg',ctypes.c_char*81)# 状态信息
,('ActiveUserID',ctypes.c_char*16)# 操作用户代码
,('BrokerOptionSelfCloseSeq',ctypes.c_int)# 经纪公司报单编号
,('BranchID',ctypes.c_char*9)# 营业部编号
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('AccountID',ctypes.c_char*13)# 资金账号
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',OptionSelfCloseRef='',UserID='',Volume=0,RequestID=0,BusinessUnit='',HedgeFlag='',OptSelfCloseFlag='',OptionSelfCloseLocalID='',ExchangeID='',ParticipantID='',ClientID='',ExchangeInstID='',TraderID='',InstallID=0,OrderSubmitStatus='',NotifySequence=0,TradingDay='',SettlementID=0,OptionSelfCloseSysID='',InsertDate='',InsertTime='',CancelTime='',ExecResult='',ClearingPartID='',SequenceNo=0,FrontID=0,SessionID=0,UserProductInfo='',StatusMsg='',ActiveUserID='',BrokerOptionSelfCloseSeq=0,BranchID='',InvestUnitID='',AccountID='',CurrencyID='',IPAddress='',MacAddress=''):
super(OptionSelfCloseField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.OptionSelfCloseRef=self._to_bytes(OptionSelfCloseRef)
self.UserID=self._to_bytes(UserID)
self.Volume=int(Volume)
self.RequestID=int(RequestID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.OptSelfCloseFlag=self._to_bytes(OptSelfCloseFlag)
self.OptionSelfCloseLocalID=self._to_bytes(OptionSelfCloseLocalID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.OrderSubmitStatus=self._to_bytes(OrderSubmitStatus)
self.NotifySequence=int(NotifySequence)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.OptionSelfCloseSysID=self._to_bytes(OptionSelfCloseSysID)
self.InsertDate=self._to_bytes(InsertDate)
self.InsertTime=self._to_bytes(InsertTime)
self.CancelTime=self._to_bytes(CancelTime)
self.ExecResult=self._to_bytes(ExecResult)
self.ClearingPartID=self._to_bytes(ClearingPartID)
self.SequenceNo=int(SequenceNo)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.UserProductInfo=self._to_bytes(UserProductInfo)
self.StatusMsg=self._to_bytes(StatusMsg)
self.ActiveUserID=self._to_bytes(ActiveUserID)
self.BrokerOptionSelfCloseSeq=int(BrokerOptionSelfCloseSeq)
self.BranchID=self._to_bytes(BranchID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.OptionSelfCloseRef=self._to_bytes(i_tuple[4])
self.UserID=self._to_bytes(i_tuple[5])
self.Volume=int(i_tuple[6])
self.RequestID=int(i_tuple[7])
self.BusinessUnit=self._to_bytes(i_tuple[8])
self.HedgeFlag=self._to_bytes(i_tuple[9])
self.OptSelfCloseFlag=self._to_bytes(i_tuple[10])
self.OptionSelfCloseLocalID=self._to_bytes(i_tuple[11])
self.ExchangeID=self._to_bytes(i_tuple[12])
self.ParticipantID=self._to_bytes(i_tuple[13])
self.ClientID=self._to_bytes(i_tuple[14])
self.ExchangeInstID=self._to_bytes(i_tuple[15])
self.TraderID=self._to_bytes(i_tuple[16])
self.InstallID=int(i_tuple[17])
self.OrderSubmitStatus=self._to_bytes(i_tuple[18])
self.NotifySequence=int(i_tuple[19])
self.TradingDay=self._to_bytes(i_tuple[20])
self.SettlementID=int(i_tuple[21])
self.OptionSelfCloseSysID=self._to_bytes(i_tuple[22])
self.InsertDate=self._to_bytes(i_tuple[23])
self.InsertTime=self._to_bytes(i_tuple[24])
self.CancelTime=self._to_bytes(i_tuple[25])
self.ExecResult=self._to_bytes(i_tuple[26])
self.ClearingPartID=self._to_bytes(i_tuple[27])
self.SequenceNo=int(i_tuple[28])
self.FrontID=int(i_tuple[29])
self.SessionID=int(i_tuple[30])
self.UserProductInfo=self._to_bytes(i_tuple[31])
self.StatusMsg=self._to_bytes(i_tuple[32])
self.ActiveUserID=self._to_bytes(i_tuple[33])
self.BrokerOptionSelfCloseSeq=int(i_tuple[34])
self.BranchID=self._to_bytes(i_tuple[35])
self.InvestUnitID=self._to_bytes(i_tuple[36])
self.AccountID=self._to_bytes(i_tuple[37])
self.CurrencyID=self._to_bytes(i_tuple[38])
self.IPAddress=self._to_bytes(i_tuple[39])
self.MacAddress=self._to_bytes(i_tuple[40])
class OptionSelfCloseActionField(Base):
"""期权自对冲操作"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('OptionSelfCloseActionRef',ctypes.c_int)# 期权自对冲操作引用
,('OptionSelfCloseRef',ctypes.c_char*13)# 期权自对冲引用
,('RequestID',ctypes.c_int)# 请求编号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('OptionSelfCloseSysID',ctypes.c_char*21)# 期权自对冲操作编号
,('ActionFlag',ctypes.c_char)# 操作标志
,('ActionDate',ctypes.c_char*9)# 操作日期
,('ActionTime',ctypes.c_char*9)# 操作时间
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('OptionSelfCloseLocalID',ctypes.c_char*13)# 本地期权自对冲编号
,('ActionLocalID',ctypes.c_char*13)# 操作本地编号
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('OrderActionStatus',ctypes.c_char)# 报单操作状态
,('UserID',ctypes.c_char*16)# 用户代码
,('StatusMsg',ctypes.c_char*81)# 状态信息
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('BranchID',ctypes.c_char*9)# 营业部编号
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',OptionSelfCloseActionRef=0,OptionSelfCloseRef='',RequestID=0,FrontID=0,SessionID=0,ExchangeID='',OptionSelfCloseSysID='',ActionFlag='',ActionDate='',ActionTime='',TraderID='',InstallID=0,OptionSelfCloseLocalID='',ActionLocalID='',ParticipantID='',ClientID='',BusinessUnit='',OrderActionStatus='',UserID='',StatusMsg='',InstrumentID='',BranchID='',InvestUnitID='',IPAddress='',MacAddress=''):
super(OptionSelfCloseActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.OptionSelfCloseActionRef=int(OptionSelfCloseActionRef)
self.OptionSelfCloseRef=self._to_bytes(OptionSelfCloseRef)
self.RequestID=int(RequestID)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.OptionSelfCloseSysID=self._to_bytes(OptionSelfCloseSysID)
self.ActionFlag=self._to_bytes(ActionFlag)
self.ActionDate=self._to_bytes(ActionDate)
self.ActionTime=self._to_bytes(ActionTime)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.OptionSelfCloseLocalID=self._to_bytes(OptionSelfCloseLocalID)
self.ActionLocalID=self._to_bytes(ActionLocalID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.OrderActionStatus=self._to_bytes(OrderActionStatus)
self.UserID=self._to_bytes(UserID)
self.StatusMsg=self._to_bytes(StatusMsg)
self.InstrumentID=self._to_bytes(InstrumentID)
self.BranchID=self._to_bytes(BranchID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.OptionSelfCloseActionRef=int(i_tuple[3])
self.OptionSelfCloseRef=self._to_bytes(i_tuple[4])
self.RequestID=int(i_tuple[5])
self.FrontID=int(i_tuple[6])
self.SessionID=int(i_tuple[7])
self.ExchangeID=self._to_bytes(i_tuple[8])
self.OptionSelfCloseSysID=self._to_bytes(i_tuple[9])
self.ActionFlag=self._to_bytes(i_tuple[10])
self.ActionDate=self._to_bytes(i_tuple[11])
self.ActionTime=self._to_bytes(i_tuple[12])
self.TraderID=self._to_bytes(i_tuple[13])
self.InstallID=int(i_tuple[14])
self.OptionSelfCloseLocalID=self._to_bytes(i_tuple[15])
self.ActionLocalID=self._to_bytes(i_tuple[16])
self.ParticipantID=self._to_bytes(i_tuple[17])
self.ClientID=self._to_bytes(i_tuple[18])
self.BusinessUnit=self._to_bytes(i_tuple[19])
self.OrderActionStatus=self._to_bytes(i_tuple[20])
self.UserID=self._to_bytes(i_tuple[21])
self.StatusMsg=self._to_bytes(i_tuple[22])
self.InstrumentID=self._to_bytes(i_tuple[23])
self.BranchID=self._to_bytes(i_tuple[24])
self.InvestUnitID=self._to_bytes(i_tuple[25])
self.IPAddress=self._to_bytes(i_tuple[26])
self.MacAddress=self._to_bytes(i_tuple[27])
class QryOptionSelfCloseField(Base):
"""期权自对冲查询"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('OptionSelfCloseSysID',ctypes.c_char*21)# 期权自对冲编号
,('InsertTimeStart',ctypes.c_char*9)# 开始时间
,('InsertTimeEnd',ctypes.c_char*9)# 结束时间
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ExchangeID='',OptionSelfCloseSysID='',InsertTimeStart='',InsertTimeEnd=''):
super(QryOptionSelfCloseField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.OptionSelfCloseSysID=self._to_bytes(OptionSelfCloseSysID)
self.InsertTimeStart=self._to_bytes(InsertTimeStart)
self.InsertTimeEnd=self._to_bytes(InsertTimeEnd)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.OptionSelfCloseSysID=self._to_bytes(i_tuple[5])
self.InsertTimeStart=self._to_bytes(i_tuple[6])
self.InsertTimeEnd=self._to_bytes(i_tuple[7])
class ExchangeOptionSelfCloseField(Base):
"""交易所期权自对冲信息"""
_fields_ = [
('Volume',ctypes.c_int)# ///数量
,('RequestID',ctypes.c_int)# 请求编号
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('OptSelfCloseFlag',ctypes.c_char)# 期权行权的头寸是否自对冲
,('OptionSelfCloseLocalID',ctypes.c_char*13)# 本地期权自对冲编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('OrderSubmitStatus',ctypes.c_char)# 期权自对冲提交状态
,('NotifySequence',ctypes.c_int)# 报单提示序号
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('OptionSelfCloseSysID',ctypes.c_char*21)# 期权自对冲编号
,('InsertDate',ctypes.c_char*9)# 报单日期
,('InsertTime',ctypes.c_char*9)# 插入时间
,('CancelTime',ctypes.c_char*9)# 撤销时间
,('ExecResult',ctypes.c_char)# 自对冲结果
,('ClearingPartID',ctypes.c_char*11)# 结算会员编号
,('SequenceNo',ctypes.c_int)# 序号
,('BranchID',ctypes.c_char*9)# 营业部编号
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,Volume= 0,RequestID=0,BusinessUnit='',HedgeFlag='',OptSelfCloseFlag='',OptionSelfCloseLocalID='',ExchangeID='',ParticipantID='',ClientID='',ExchangeInstID='',TraderID='',InstallID=0,OrderSubmitStatus='',NotifySequence=0,TradingDay='',SettlementID=0,OptionSelfCloseSysID='',InsertDate='',InsertTime='',CancelTime='',ExecResult='',ClearingPartID='',SequenceNo=0,BranchID='',IPAddress='',MacAddress=''):
super(ExchangeOptionSelfCloseField,self).__init__()
self.Volume=int(Volume)
self.RequestID=int(RequestID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.OptSelfCloseFlag=self._to_bytes(OptSelfCloseFlag)
self.OptionSelfCloseLocalID=self._to_bytes(OptionSelfCloseLocalID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.OrderSubmitStatus=self._to_bytes(OrderSubmitStatus)
self.NotifySequence=int(NotifySequence)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.OptionSelfCloseSysID=self._to_bytes(OptionSelfCloseSysID)
self.InsertDate=self._to_bytes(InsertDate)
self.InsertTime=self._to_bytes(InsertTime)
self.CancelTime=self._to_bytes(CancelTime)
self.ExecResult=self._to_bytes(ExecResult)
self.ClearingPartID=self._to_bytes(ClearingPartID)
self.SequenceNo=int(SequenceNo)
self.BranchID=self._to_bytes(BranchID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.Volume=int(i_tuple[1])
self.RequestID=int(i_tuple[2])
self.BusinessUnit=self._to_bytes(i_tuple[3])
self.HedgeFlag=self._to_bytes(i_tuple[4])
self.OptSelfCloseFlag=self._to_bytes(i_tuple[5])
self.OptionSelfCloseLocalID=self._to_bytes(i_tuple[6])
self.ExchangeID=self._to_bytes(i_tuple[7])
self.ParticipantID=self._to_bytes(i_tuple[8])
self.ClientID=self._to_bytes(i_tuple[9])
self.ExchangeInstID=self._to_bytes(i_tuple[10])
self.TraderID=self._to_bytes(i_tuple[11])
self.InstallID=int(i_tuple[12])
self.OrderSubmitStatus=self._to_bytes(i_tuple[13])
self.NotifySequence=int(i_tuple[14])
self.TradingDay=self._to_bytes(i_tuple[15])
self.SettlementID=int(i_tuple[16])
self.OptionSelfCloseSysID=self._to_bytes(i_tuple[17])
self.InsertDate=self._to_bytes(i_tuple[18])
self.InsertTime=self._to_bytes(i_tuple[19])
self.CancelTime=self._to_bytes(i_tuple[20])
self.ExecResult=self._to_bytes(i_tuple[21])
self.ClearingPartID=self._to_bytes(i_tuple[22])
self.SequenceNo=int(i_tuple[23])
self.BranchID=self._to_bytes(i_tuple[24])
self.IPAddress=self._to_bytes(i_tuple[25])
self.MacAddress=self._to_bytes(i_tuple[26])
class QryOptionSelfCloseActionField(Base):
"""期权自对冲操作查询"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
]
def __init__(self,BrokerID= '',InvestorID='',ExchangeID=''):
super(QryOptionSelfCloseActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
class ExchangeOptionSelfCloseActionField(Base):
"""交易所期权自对冲操作"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('OptionSelfCloseSysID',ctypes.c_char*21)# 期权自对冲操作编号
,('ActionFlag',ctypes.c_char)# 操作标志
,('ActionDate',ctypes.c_char*9)# 操作日期
,('ActionTime',ctypes.c_char*9)# 操作时间
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('OptionSelfCloseLocalID',ctypes.c_char*13)# 本地期权自对冲编号
,('ActionLocalID',ctypes.c_char*13)# 操作本地编号
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('OrderActionStatus',ctypes.c_char)# 报单操作状态
,('UserID',ctypes.c_char*16)# 用户代码
,('BranchID',ctypes.c_char*9)# 营业部编号
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,ExchangeID= '',OptionSelfCloseSysID='',ActionFlag='',ActionDate='',ActionTime='',TraderID='',InstallID=0,OptionSelfCloseLocalID='',ActionLocalID='',ParticipantID='',ClientID='',BusinessUnit='',OrderActionStatus='',UserID='',BranchID='',IPAddress='',MacAddress=''):
super(ExchangeOptionSelfCloseActionField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.OptionSelfCloseSysID=self._to_bytes(OptionSelfCloseSysID)
self.ActionFlag=self._to_bytes(ActionFlag)
self.ActionDate=self._to_bytes(ActionDate)
self.ActionTime=self._to_bytes(ActionTime)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.OptionSelfCloseLocalID=self._to_bytes(OptionSelfCloseLocalID)
self.ActionLocalID=self._to_bytes(ActionLocalID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.OrderActionStatus=self._to_bytes(OrderActionStatus)
self.UserID=self._to_bytes(UserID)
self.BranchID=self._to_bytes(BranchID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.OptionSelfCloseSysID=self._to_bytes(i_tuple[2])
self.ActionFlag=self._to_bytes(i_tuple[3])
self.ActionDate=self._to_bytes(i_tuple[4])
self.ActionTime=self._to_bytes(i_tuple[5])
self.TraderID=self._to_bytes(i_tuple[6])
self.InstallID=int(i_tuple[7])
self.OptionSelfCloseLocalID=self._to_bytes(i_tuple[8])
self.ActionLocalID=self._to_bytes(i_tuple[9])
self.ParticipantID=self._to_bytes(i_tuple[10])
self.ClientID=self._to_bytes(i_tuple[11])
self.BusinessUnit=self._to_bytes(i_tuple[12])
self.OrderActionStatus=self._to_bytes(i_tuple[13])
self.UserID=self._to_bytes(i_tuple[14])
self.BranchID=self._to_bytes(i_tuple[15])
self.IPAddress=self._to_bytes(i_tuple[16])
self.MacAddress=self._to_bytes(i_tuple[17])
class SyncDelaySwapField(Base):
"""延时换汇同步"""
_fields_ = [
('DelaySwapSeqNo',ctypes.c_char*15)# ///换汇流水号
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('FromCurrencyID',ctypes.c_char*4)# 源币种
,('FromAmount',ctypes.c_double)# 源金额
,('FromFrozenSwap',ctypes.c_double)# 源换汇冻结金额(可用冻结)
,('FromRemainSwap',ctypes.c_double)# 源剩余换汇额度(可提冻结)
,('ToCurrencyID',ctypes.c_char*4)# 目标币种
,('ToAmount',ctypes.c_double)# 目标金额
]
def __init__(self,DelaySwapSeqNo= '',BrokerID='',InvestorID='',FromCurrencyID='',FromAmount=0.0,FromFrozenSwap=0.0,FromRemainSwap=0.0,ToCurrencyID='',ToAmount=0.0):
super(SyncDelaySwapField,self).__init__()
self.DelaySwapSeqNo=self._to_bytes(DelaySwapSeqNo)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.FromCurrencyID=self._to_bytes(FromCurrencyID)
self.FromAmount=float(FromAmount)
self.FromFrozenSwap=float(FromFrozenSwap)
self.FromRemainSwap=float(FromRemainSwap)
self.ToCurrencyID=self._to_bytes(ToCurrencyID)
self.ToAmount=float(ToAmount)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.DelaySwapSeqNo=self._to_bytes(i_tuple[1])
self.BrokerID=self._to_bytes(i_tuple[2])
self.InvestorID=self._to_bytes(i_tuple[3])
self.FromCurrencyID=self._to_bytes(i_tuple[4])
self.FromAmount=float(i_tuple[5])
self.FromFrozenSwap=float(i_tuple[6])
self.FromRemainSwap=float(i_tuple[7])
self.ToCurrencyID=self._to_bytes(i_tuple[8])
self.ToAmount=float(i_tuple[9])
class QrySyncDelaySwapField(Base):
"""查询延时换汇同步"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('DelaySwapSeqNo',ctypes.c_char*15)# 延时换汇流水号
]
def __init__(self,BrokerID= '',DelaySwapSeqNo=''):
super(QrySyncDelaySwapField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.DelaySwapSeqNo=self._to_bytes(DelaySwapSeqNo)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.DelaySwapSeqNo=self._to_bytes(i_tuple[2])
class InvestUnitField(Base):
"""投资单元"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('InvestorUnitName',ctypes.c_char*81)# 投资者单元名称
,('InvestorGroupID',ctypes.c_char*13)# 投资者分组代码
,('CommModelID',ctypes.c_char*13)# 手续费率模板代码
,('MarginModelID',ctypes.c_char*13)# 保证金率模板代码
,('AccountID',ctypes.c_char*13)# 资金账号
,('CurrencyID',ctypes.c_char*4)# 币种代码
]
def __init__(self,BrokerID= '',InvestorID='',InvestUnitID='',InvestorUnitName='',InvestorGroupID='',CommModelID='',MarginModelID='',AccountID='',CurrencyID=''):
super(InvestUnitField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.InvestorUnitName=self._to_bytes(InvestorUnitName)
self.InvestorGroupID=self._to_bytes(InvestorGroupID)
self.CommModelID=self._to_bytes(CommModelID)
self.MarginModelID=self._to_bytes(MarginModelID)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InvestUnitID=self._to_bytes(i_tuple[3])
self.InvestorUnitName=self._to_bytes(i_tuple[4])
self.InvestorGroupID=self._to_bytes(i_tuple[5])
self.CommModelID=self._to_bytes(i_tuple[6])
self.MarginModelID=self._to_bytes(i_tuple[7])
self.AccountID=self._to_bytes(i_tuple[8])
self.CurrencyID=self._to_bytes(i_tuple[9])
class QryInvestUnitField(Base):
"""查询投资单元"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InvestUnitID=''):
super(QryInvestUnitField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InvestUnitID=self._to_bytes(i_tuple[3])
class SecAgentCheckModeField(Base):
"""二级代理商资金校验模式"""
_fields_ = [
('InvestorID',ctypes.c_char*13)# ///投资者代码
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('CurrencyID',ctypes.c_char*4)# 币种
,('BrokerSecAgentID',ctypes.c_char*13)# 境外中介机构资金帐号
,('CheckSelfAccount',ctypes.c_int)# 是否需要校验自己的资金账户
]
def __init__(self,InvestorID= '',BrokerID='',CurrencyID='',BrokerSecAgentID='',CheckSelfAccount=0):
super(SecAgentCheckModeField,self).__init__()
self.InvestorID=self._to_bytes(InvestorID)
self.BrokerID=self._to_bytes(BrokerID)
self.CurrencyID=self._to_bytes(CurrencyID)
self.BrokerSecAgentID=self._to_bytes(BrokerSecAgentID)
self.CheckSelfAccount=int(CheckSelfAccount)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InvestorID=self._to_bytes(i_tuple[1])
self.BrokerID=self._to_bytes(i_tuple[2])
self.CurrencyID=self._to_bytes(i_tuple[3])
self.BrokerSecAgentID=self._to_bytes(i_tuple[4])
self.CheckSelfAccount=int(i_tuple[5])
class MarketDataField(Base):
"""市场行情"""
_fields_ = [
('TradingDay',ctypes.c_char*9)# ///交易日
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('LastPrice',ctypes.c_double)# 最新价
,('PreSettlementPrice',ctypes.c_double)# 上次结算价
,('PreClosePrice',ctypes.c_double)# 昨收盘
,('PreOpenInterest',ctypes.c_double)# 昨持仓量
,('OpenPrice',ctypes.c_double)# 今开盘
,('HighestPrice',ctypes.c_double)# 最高价
,('LowestPrice',ctypes.c_double)# 最低价
,('Volume',ctypes.c_int)# 数量
,('Turnover',ctypes.c_double)# 成交金额
,('OpenInterest',ctypes.c_double)# 持仓量
,('ClosePrice',ctypes.c_double)# 今收盘
,('SettlementPrice',ctypes.c_double)# 本次结算价
,('UpperLimitPrice',ctypes.c_double)# 涨停板价
,('LowerLimitPrice',ctypes.c_double)# 跌停板价
,('PreDelta',ctypes.c_double)# 昨虚实度
,('CurrDelta',ctypes.c_double)# 今虚实度
,('UpdateTime',ctypes.c_char*9)# 最后修改时间
,('UpdateMillisec',ctypes.c_int)# 最后修改毫秒
,('ActionDay',ctypes.c_char*9)# 业务日期
]
def __init__(self,TradingDay= '',InstrumentID='',ExchangeID='',ExchangeInstID='',LastPrice=0.0,PreSettlementPrice=0.0,PreClosePrice=0.0,PreOpenInterest=0.0,OpenPrice=0.0,HighestPrice=0.0,LowestPrice=0.0,Volume=0,Turnover=0.0,OpenInterest=0.0,ClosePrice=0.0,SettlementPrice=0.0,UpperLimitPrice=0.0,LowerLimitPrice=0.0,PreDelta=0.0,CurrDelta=0.0,UpdateTime='',UpdateMillisec=0,ActionDay=''):
super(MarketDataField,self).__init__()
self.TradingDay=self._to_bytes(TradingDay)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.LastPrice=float(LastPrice)
self.PreSettlementPrice=float(PreSettlementPrice)
self.PreClosePrice=float(PreClosePrice)
self.PreOpenInterest=float(PreOpenInterest)
self.OpenPrice=float(OpenPrice)
self.HighestPrice=float(HighestPrice)
self.LowestPrice=float(LowestPrice)
self.Volume=int(Volume)
self.Turnover=float(Turnover)
self.OpenInterest=float(OpenInterest)
self.ClosePrice=float(ClosePrice)
self.SettlementPrice=float(SettlementPrice)
self.UpperLimitPrice=float(UpperLimitPrice)
self.LowerLimitPrice=float(LowerLimitPrice)
self.PreDelta=float(PreDelta)
self.CurrDelta=float(CurrDelta)
self.UpdateTime=self._to_bytes(UpdateTime)
self.UpdateMillisec=int(UpdateMillisec)
self.ActionDay=self._to_bytes(ActionDay)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradingDay=self._to_bytes(i_tuple[1])
self.InstrumentID=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
self.ExchangeInstID=self._to_bytes(i_tuple[4])
self.LastPrice=float(i_tuple[5])
self.PreSettlementPrice=float(i_tuple[6])
self.PreClosePrice=float(i_tuple[7])
self.PreOpenInterest=float(i_tuple[8])
self.OpenPrice=float(i_tuple[9])
self.HighestPrice=float(i_tuple[10])
self.LowestPrice=float(i_tuple[11])
self.Volume=int(i_tuple[12])
self.Turnover=float(i_tuple[13])
self.OpenInterest=float(i_tuple[14])
self.ClosePrice=float(i_tuple[15])
self.SettlementPrice=float(i_tuple[16])
self.UpperLimitPrice=float(i_tuple[17])
self.LowerLimitPrice=float(i_tuple[18])
self.PreDelta=float(i_tuple[19])
self.CurrDelta=float(i_tuple[20])
self.UpdateTime=self._to_bytes(i_tuple[21])
self.UpdateMillisec=int(i_tuple[22])
self.ActionDay=self._to_bytes(i_tuple[23])
class MarketDataBaseField(Base):
"""行情基础属性"""
_fields_ = [
('TradingDay',ctypes.c_char*9)# ///交易日
,('PreSettlementPrice',ctypes.c_double)# 上次结算价
,('PreClosePrice',ctypes.c_double)# 昨收盘
,('PreOpenInterest',ctypes.c_double)# 昨持仓量
,('PreDelta',ctypes.c_double)# 昨虚实度
]
def __init__(self,TradingDay= '',PreSettlementPrice=0.0,PreClosePrice=0.0,PreOpenInterest=0.0,PreDelta=0.0):
super(MarketDataBaseField,self).__init__()
self.TradingDay=self._to_bytes(TradingDay)
self.PreSettlementPrice=float(PreSettlementPrice)
self.PreClosePrice=float(PreClosePrice)
self.PreOpenInterest=float(PreOpenInterest)
self.PreDelta=float(PreDelta)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradingDay=self._to_bytes(i_tuple[1])
self.PreSettlementPrice=float(i_tuple[2])
self.PreClosePrice=float(i_tuple[3])
self.PreOpenInterest=float(i_tuple[4])
self.PreDelta=float(i_tuple[5])
class MarketDataStaticField(Base):
"""行情静态属性"""
_fields_ = [
('OpenPrice',ctypes.c_double)# ///今开盘
,('HighestPrice',ctypes.c_double)# 最高价
,('LowestPrice',ctypes.c_double)# 最低价
,('ClosePrice',ctypes.c_double)# 今收盘
,('UpperLimitPrice',ctypes.c_double)# 涨停板价
,('LowerLimitPrice',ctypes.c_double)# 跌停板价
,('SettlementPrice',ctypes.c_double)# 本次结算价
,('CurrDelta',ctypes.c_double)# 今虚实度
]
def __init__(self,OpenPrice= 0.0,HighestPrice=0.0,LowestPrice=0.0,ClosePrice=0.0,UpperLimitPrice=0.0,LowerLimitPrice=0.0,SettlementPrice=0.0,CurrDelta=0.0):
super(MarketDataStaticField,self).__init__()
self.OpenPrice=float(OpenPrice)
self.HighestPrice=float(HighestPrice)
self.LowestPrice=float(LowestPrice)
self.ClosePrice=float(ClosePrice)
self.UpperLimitPrice=float(UpperLimitPrice)
self.LowerLimitPrice=float(LowerLimitPrice)
self.SettlementPrice=float(SettlementPrice)
self.CurrDelta=float(CurrDelta)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.OpenPrice=float(i_tuple[1])
self.HighestPrice=float(i_tuple[2])
self.LowestPrice=float(i_tuple[3])
self.ClosePrice=float(i_tuple[4])
self.UpperLimitPrice=float(i_tuple[5])
self.LowerLimitPrice=float(i_tuple[6])
self.SettlementPrice=float(i_tuple[7])
self.CurrDelta=float(i_tuple[8])
class MarketDataLastMatchField(Base):
"""行情最新成交属性"""
_fields_ = [
('LastPrice',ctypes.c_double)# ///最新价
,('Volume',ctypes.c_int)# 数量
,('Turnover',ctypes.c_double)# 成交金额
,('OpenInterest',ctypes.c_double)# 持仓量
]
def __init__(self,LastPrice= 0.0,Volume=0,Turnover=0.0,OpenInterest=0.0):
super(MarketDataLastMatchField,self).__init__()
self.LastPrice=float(LastPrice)
self.Volume=int(Volume)
self.Turnover=float(Turnover)
self.OpenInterest=float(OpenInterest)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.LastPrice=float(i_tuple[1])
self.Volume=int(i_tuple[2])
self.Turnover=float(i_tuple[3])
self.OpenInterest=float(i_tuple[4])
class MarketDataBestPriceField(Base):
"""行情最优价属性"""
_fields_ = [
('BidPrice1',ctypes.c_double)# ///申买价一
,('BidVolume1',ctypes.c_int)# 申买量一
,('AskPrice1',ctypes.c_double)# 申卖价一
,('AskVolume1',ctypes.c_int)# 申卖量一
]
def __init__(self,BidPrice1= 0.0,BidVolume1=0,AskPrice1=0.0,AskVolume1=0):
super(MarketDataBestPriceField,self).__init__()
self.BidPrice1=float(BidPrice1)
self.BidVolume1=int(BidVolume1)
self.AskPrice1=float(AskPrice1)
self.AskVolume1=int(AskVolume1)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BidPrice1=float(i_tuple[1])
self.BidVolume1=int(i_tuple[2])
self.AskPrice1=float(i_tuple[3])
self.AskVolume1=int(i_tuple[4])
class MarketDataBid23Field(Base):
"""行情申买二、三属性"""
_fields_ = [
('BidPrice2',ctypes.c_double)# ///申买价二
,('BidVolume2',ctypes.c_int)# 申买量二
,('BidPrice3',ctypes.c_double)# 申买价三
,('BidVolume3',ctypes.c_int)# 申买量三
]
def __init__(self,BidPrice2= 0.0,BidVolume2=0,BidPrice3=0.0,BidVolume3=0):
super(MarketDataBid23Field,self).__init__()
self.BidPrice2=float(BidPrice2)
self.BidVolume2=int(BidVolume2)
self.BidPrice3=float(BidPrice3)
self.BidVolume3=int(BidVolume3)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BidPrice2=float(i_tuple[1])
self.BidVolume2=int(i_tuple[2])
self.BidPrice3=float(i_tuple[3])
self.BidVolume3=int(i_tuple[4])
class MarketDataAsk23Field(Base):
"""行情申卖二、三属性"""
_fields_ = [
('AskPrice2',ctypes.c_double)# ///申卖价二
,('AskVolume2',ctypes.c_int)# 申卖量二
,('AskPrice3',ctypes.c_double)# 申卖价三
,('AskVolume3',ctypes.c_int)# 申卖量三
]
def __init__(self,AskPrice2= 0.0,AskVolume2=0,AskPrice3=0.0,AskVolume3=0):
super(MarketDataAsk23Field,self).__init__()
self.AskPrice2=float(AskPrice2)
self.AskVolume2=int(AskVolume2)
self.AskPrice3=float(AskPrice3)
self.AskVolume3=int(AskVolume3)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.AskPrice2=float(i_tuple[1])
self.AskVolume2=int(i_tuple[2])
self.AskPrice3=float(i_tuple[3])
self.AskVolume3=int(i_tuple[4])
class MarketDataBid45Field(Base):
"""行情申买四、五属性"""
_fields_ = [
('BidPrice4',ctypes.c_double)# ///申买价四
,('BidVolume4',ctypes.c_int)# 申买量四
,('BidPrice5',ctypes.c_double)# 申买价五
,('BidVolume5',ctypes.c_int)# 申买量五
]
def __init__(self,BidPrice4= 0.0,BidVolume4=0,BidPrice5=0.0,BidVolume5=0):
super(MarketDataBid45Field,self).__init__()
self.BidPrice4=float(BidPrice4)
self.BidVolume4=int(BidVolume4)
self.BidPrice5=float(BidPrice5)
self.BidVolume5=int(BidVolume5)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BidPrice4=float(i_tuple[1])
self.BidVolume4=int(i_tuple[2])
self.BidPrice5=float(i_tuple[3])
self.BidVolume5=int(i_tuple[4])
class MarketDataAsk45Field(Base):
"""行情申卖四、五属性"""
_fields_ = [
('AskPrice4',ctypes.c_double)# ///申卖价四
,('AskVolume4',ctypes.c_int)# 申卖量四
,('AskPrice5',ctypes.c_double)# 申卖价五
,('AskVolume5',ctypes.c_int)# 申卖量五
]
def __init__(self,AskPrice4= 0.0,AskVolume4=0,AskPrice5=0.0,AskVolume5=0):
super(MarketDataAsk45Field,self).__init__()
self.AskPrice4=float(AskPrice4)
self.AskVolume4=int(AskVolume4)
self.AskPrice5=float(AskPrice5)
self.AskVolume5=int(AskVolume5)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.AskPrice4=float(i_tuple[1])
self.AskVolume4=int(i_tuple[2])
self.AskPrice5=float(i_tuple[3])
self.AskVolume5=int(i_tuple[4])
class MarketDataUpdateTimeField(Base):
"""行情更新时间属性"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('UpdateTime',ctypes.c_char*9)# 最后修改时间
,('UpdateMillisec',ctypes.c_int)# 最后修改毫秒
,('ActionDay',ctypes.c_char*9)# 业务日期
]
def __init__(self,InstrumentID= '',UpdateTime='',UpdateMillisec=0,ActionDay=''):
super(MarketDataUpdateTimeField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.UpdateTime=self._to_bytes(UpdateTime)
self.UpdateMillisec=int(UpdateMillisec)
self.ActionDay=self._to_bytes(ActionDay)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.UpdateTime=self._to_bytes(i_tuple[2])
self.UpdateMillisec=int(i_tuple[3])
self.ActionDay=self._to_bytes(i_tuple[4])
class MarketDataExchangeField(Base):
"""行情交易所代码属性"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
]
def __init__(self,ExchangeID= ''):
super(MarketDataExchangeField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
class SpecificInstrumentField(Base):
"""指定的合约"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
]
def __init__(self,InstrumentID= ''):
super(SpecificInstrumentField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
class InstrumentStatusField(Base):
"""合约状态"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('SettlementGroupID',ctypes.c_char*9)# 结算组代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('InstrumentStatus',ctypes.c_char)# 合约交易状态
,('TradingSegmentSN',ctypes.c_int)# 交易阶段编号
,('EnterTime',ctypes.c_char*9)# 进入本状态时间
,('EnterReason',ctypes.c_char)# 进入本状态原因
]
def __init__(self,ExchangeID= '',ExchangeInstID='',SettlementGroupID='',InstrumentID='',InstrumentStatus='',TradingSegmentSN=0,EnterTime='',EnterReason=''):
super(InstrumentStatusField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.SettlementGroupID=self._to_bytes(SettlementGroupID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.InstrumentStatus=self._to_bytes(InstrumentStatus)
self.TradingSegmentSN=int(TradingSegmentSN)
self.EnterTime=self._to_bytes(EnterTime)
self.EnterReason=self._to_bytes(EnterReason)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.ExchangeInstID=self._to_bytes(i_tuple[2])
self.SettlementGroupID=self._to_bytes(i_tuple[3])
self.InstrumentID=self._to_bytes(i_tuple[4])
self.InstrumentStatus=self._to_bytes(i_tuple[5])
self.TradingSegmentSN=int(i_tuple[6])
self.EnterTime=self._to_bytes(i_tuple[7])
self.EnterReason=self._to_bytes(i_tuple[8])
class QryInstrumentStatusField(Base):
"""查询合约状态"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
]
def __init__(self,ExchangeID= '',ExchangeInstID=''):
super(QryInstrumentStatusField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.ExchangeInstID=self._to_bytes(i_tuple[2])
class InvestorAccountField(Base):
"""投资者账户"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('CurrencyID',ctypes.c_char*4)# 币种代码
]
def __init__(self,BrokerID= '',InvestorID='',AccountID='',CurrencyID=''):
super(InvestorAccountField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.AccountID=self._to_bytes(i_tuple[3])
self.CurrencyID=self._to_bytes(i_tuple[4])
class PositionProfitAlgorithmField(Base):
"""浮动盈亏算法"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Algorithm',ctypes.c_char)# 盈亏算法
,('Memo',ctypes.c_char*161)# 备注
,('CurrencyID',ctypes.c_char*4)# 币种代码
]
def __init__(self,BrokerID= '',AccountID='',Algorithm='',Memo='',CurrencyID=''):
super(PositionProfitAlgorithmField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.AccountID=self._to_bytes(AccountID)
self.Algorithm=self._to_bytes(Algorithm)
self.Memo=self._to_bytes(Memo)
self.CurrencyID=self._to_bytes(CurrencyID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.AccountID=self._to_bytes(i_tuple[2])
self.Algorithm=self._to_bytes(i_tuple[3])
self.Memo=self._to_bytes(i_tuple[4])
self.CurrencyID=self._to_bytes(i_tuple[5])
class DiscountField(Base):
"""会员资金折扣"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('Discount',ctypes.c_double)# 资金折扣比例
]
def __init__(self,BrokerID= '',InvestorRange='',InvestorID='',Discount=0.0):
super(DiscountField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.InvestorID=self._to_bytes(InvestorID)
self.Discount=float(Discount)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.InvestorID=self._to_bytes(i_tuple[3])
self.Discount=float(i_tuple[4])
class QryTransferBankField(Base):
"""查询转帐银行"""
_fields_ = [
('BankID',ctypes.c_char*4)# ///银行代码
,('BankBrchID',ctypes.c_char*5)# 银行分中心代码
]
def __init__(self,BankID= '',BankBrchID=''):
super(QryTransferBankField,self).__init__()
self.BankID=self._to_bytes(BankID)
self.BankBrchID=self._to_bytes(BankBrchID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BankID=self._to_bytes(i_tuple[1])
self.BankBrchID=self._to_bytes(i_tuple[2])
class TransferBankField(Base):
"""转帐银行"""
_fields_ = [
('BankID',ctypes.c_char*4)# ///银行代码
,('BankBrchID',ctypes.c_char*5)# 银行分中心代码
,('BankName',ctypes.c_char*101)# 银行名称
,('IsActive',ctypes.c_int)# 是否活跃
]
def __init__(self,BankID= '',BankBrchID='',BankName='',IsActive=0):
super(TransferBankField,self).__init__()
self.BankID=self._to_bytes(BankID)
self.BankBrchID=self._to_bytes(BankBrchID)
self.BankName=self._to_bytes(BankName)
self.IsActive=int(IsActive)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BankID=self._to_bytes(i_tuple[1])
self.BankBrchID=self._to_bytes(i_tuple[2])
self.BankName=self._to_bytes(i_tuple[3])
self.IsActive=int(i_tuple[4])
class QryInvestorPositionDetailField(Base):
"""查询投资者持仓明细"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ExchangeID='',InvestUnitID=''):
super(QryInvestorPositionDetailField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.InvestUnitID=self._to_bytes(i_tuple[5])
class InvestorPositionDetailField(Base):
"""投资者持仓明细"""
_fields_ = [
('InstrumentID',ctypes.c_char*31)# ///合约代码
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('Direction',ctypes.c_char)# 买卖
,('OpenDate',ctypes.c_char*9)# 开仓日期
,('TradeID',ctypes.c_char*21)# 成交编号
,('Volume',ctypes.c_int)# 数量
,('OpenPrice',ctypes.c_double)# 开仓价
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('TradeType',ctypes.c_char)# 成交类型
,('CombInstrumentID',ctypes.c_char*31)# 组合合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('CloseProfitByDate',ctypes.c_double)# 逐日盯市平仓盈亏
,('CloseProfitByTrade',ctypes.c_double)# 逐笔对冲平仓盈亏
,('PositionProfitByDate',ctypes.c_double)# 逐日盯市持仓盈亏
,('PositionProfitByTrade',ctypes.c_double)# 逐笔对冲持仓盈亏
,('Margin',ctypes.c_double)# 投资者保证金
,('ExchMargin',ctypes.c_double)# 交易所保证金
,('MarginRateByMoney',ctypes.c_double)# 保证金率
,('MarginRateByVolume',ctypes.c_double)# 保证金率(按手数)
,('LastSettlementPrice',ctypes.c_double)# 昨结算价
,('SettlementPrice',ctypes.c_double)# 结算价
,('CloseVolume',ctypes.c_int)# 平仓量
,('CloseAmount',ctypes.c_double)# 平仓金额
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,InstrumentID= '',BrokerID='',InvestorID='',HedgeFlag='',Direction='',OpenDate='',TradeID='',Volume=0,OpenPrice=0.0,TradingDay='',SettlementID=0,TradeType='',CombInstrumentID='',ExchangeID='',CloseProfitByDate=0.0,CloseProfitByTrade=0.0,PositionProfitByDate=0.0,PositionProfitByTrade=0.0,Margin=0.0,ExchMargin=0.0,MarginRateByMoney=0.0,MarginRateByVolume=0.0,LastSettlementPrice=0.0,SettlementPrice=0.0,CloseVolume=0,CloseAmount=0.0,InvestUnitID=''):
super(InvestorPositionDetailField,self).__init__()
self.InstrumentID=self._to_bytes(InstrumentID)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.Direction=self._to_bytes(Direction)
self.OpenDate=self._to_bytes(OpenDate)
self.TradeID=self._to_bytes(TradeID)
self.Volume=int(Volume)
self.OpenPrice=float(OpenPrice)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.TradeType=self._to_bytes(TradeType)
self.CombInstrumentID=self._to_bytes(CombInstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.CloseProfitByDate=float(CloseProfitByDate)
self.CloseProfitByTrade=float(CloseProfitByTrade)
self.PositionProfitByDate=float(PositionProfitByDate)
self.PositionProfitByTrade=float(PositionProfitByTrade)
self.Margin=float(Margin)
self.ExchMargin=float(ExchMargin)
self.MarginRateByMoney=float(MarginRateByMoney)
self.MarginRateByVolume=float(MarginRateByVolume)
self.LastSettlementPrice=float(LastSettlementPrice)
self.SettlementPrice=float(SettlementPrice)
self.CloseVolume=int(CloseVolume)
self.CloseAmount=float(CloseAmount)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.InstrumentID=self._to_bytes(i_tuple[1])
self.BrokerID=self._to_bytes(i_tuple[2])
self.InvestorID=self._to_bytes(i_tuple[3])
self.HedgeFlag=self._to_bytes(i_tuple[4])
self.Direction=self._to_bytes(i_tuple[5])
self.OpenDate=self._to_bytes(i_tuple[6])
self.TradeID=self._to_bytes(i_tuple[7])
self.Volume=int(i_tuple[8])
self.OpenPrice=float(i_tuple[9])
self.TradingDay=self._to_bytes(i_tuple[10])
self.SettlementID=int(i_tuple[11])
self.TradeType=self._to_bytes(i_tuple[12])
self.CombInstrumentID=self._to_bytes(i_tuple[13])
self.ExchangeID=self._to_bytes(i_tuple[14])
self.CloseProfitByDate=float(i_tuple[15])
self.CloseProfitByTrade=float(i_tuple[16])
self.PositionProfitByDate=float(i_tuple[17])
self.PositionProfitByTrade=float(i_tuple[18])
self.Margin=float(i_tuple[19])
self.ExchMargin=float(i_tuple[20])
self.MarginRateByMoney=float(i_tuple[21])
self.MarginRateByVolume=float(i_tuple[22])
self.LastSettlementPrice=float(i_tuple[23])
self.SettlementPrice=float(i_tuple[24])
self.CloseVolume=int(i_tuple[25])
self.CloseAmount=float(i_tuple[26])
self.InvestUnitID=self._to_bytes(i_tuple[27])
class TradingAccountPasswordField(Base):
"""资金账户口令域"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 密码
,('CurrencyID',ctypes.c_char*4)# 币种代码
]
def __init__(self,BrokerID= '',AccountID='',Password='',CurrencyID=''):
super(TradingAccountPasswordField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.CurrencyID=self._to_bytes(CurrencyID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.AccountID=self._to_bytes(i_tuple[2])
self.Password=self._to_bytes(i_tuple[3])
self.CurrencyID=self._to_bytes(i_tuple[4])
class MDTraderOfferField(Base):
"""交易所行情报盘机"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('Password',ctypes.c_char*41)# 密码
,('InstallID',ctypes.c_int)# 安装编号
,('OrderLocalID',ctypes.c_char*13)# 本地报单编号
,('TraderConnectStatus',ctypes.c_char)# 交易所交易员连接状态
,('ConnectRequestDate',ctypes.c_char*9)# 发出连接请求的日期
,('ConnectRequestTime',ctypes.c_char*9)# 发出连接请求的时间
,('LastReportDate',ctypes.c_char*9)# 上次报告日期
,('LastReportTime',ctypes.c_char*9)# 上次报告时间
,('ConnectDate',ctypes.c_char*9)# 完成连接日期
,('ConnectTime',ctypes.c_char*9)# 完成连接时间
,('StartDate',ctypes.c_char*9)# 启动日期
,('StartTime',ctypes.c_char*9)# 启动时间
,('TradingDay',ctypes.c_char*9)# 交易日
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('MaxTradeID',ctypes.c_char*21)# 本席位最大成交编号
,('MaxOrderMessageReference',ctypes.c_char*7)# 本席位最大报单备拷
]
def __init__(self,ExchangeID= '',TraderID='',ParticipantID='',Password='',InstallID=0,OrderLocalID='',TraderConnectStatus='',ConnectRequestDate='',ConnectRequestTime='',LastReportDate='',LastReportTime='',ConnectDate='',ConnectTime='',StartDate='',StartTime='',TradingDay='',BrokerID='',MaxTradeID='',MaxOrderMessageReference=''):
super(MDTraderOfferField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.TraderID=self._to_bytes(TraderID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.Password=self._to_bytes(Password)
self.InstallID=int(InstallID)
self.OrderLocalID=self._to_bytes(OrderLocalID)
self.TraderConnectStatus=self._to_bytes(TraderConnectStatus)
self.ConnectRequestDate=self._to_bytes(ConnectRequestDate)
self.ConnectRequestTime=self._to_bytes(ConnectRequestTime)
self.LastReportDate=self._to_bytes(LastReportDate)
self.LastReportTime=self._to_bytes(LastReportTime)
self.ConnectDate=self._to_bytes(ConnectDate)
self.ConnectTime=self._to_bytes(ConnectTime)
self.StartDate=self._to_bytes(StartDate)
self.StartTime=self._to_bytes(StartTime)
self.TradingDay=self._to_bytes(TradingDay)
self.BrokerID=self._to_bytes(BrokerID)
self.MaxTradeID=self._to_bytes(MaxTradeID)
self.MaxOrderMessageReference=self._to_bytes(MaxOrderMessageReference)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.TraderID=self._to_bytes(i_tuple[2])
self.ParticipantID=self._to_bytes(i_tuple[3])
self.Password=self._to_bytes(i_tuple[4])
self.InstallID=int(i_tuple[5])
self.OrderLocalID=self._to_bytes(i_tuple[6])
self.TraderConnectStatus=self._to_bytes(i_tuple[7])
self.ConnectRequestDate=self._to_bytes(i_tuple[8])
self.ConnectRequestTime=self._to_bytes(i_tuple[9])
self.LastReportDate=self._to_bytes(i_tuple[10])
self.LastReportTime=self._to_bytes(i_tuple[11])
self.ConnectDate=self._to_bytes(i_tuple[12])
self.ConnectTime=self._to_bytes(i_tuple[13])
self.StartDate=self._to_bytes(i_tuple[14])
self.StartTime=self._to_bytes(i_tuple[15])
self.TradingDay=self._to_bytes(i_tuple[16])
self.BrokerID=self._to_bytes(i_tuple[17])
self.MaxTradeID=self._to_bytes(i_tuple[18])
self.MaxOrderMessageReference=self._to_bytes(i_tuple[19])
class QryMDTraderOfferField(Base):
"""查询行情报盘机"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
]
def __init__(self,ExchangeID= '',ParticipantID='',TraderID=''):
super(QryMDTraderOfferField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.TraderID=self._to_bytes(TraderID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.ParticipantID=self._to_bytes(i_tuple[2])
self.TraderID=self._to_bytes(i_tuple[3])
class QryNoticeField(Base):
"""查询客户通知"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
]
def __init__(self,BrokerID= ''):
super(QryNoticeField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
class NoticeField(Base):
"""客户通知"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('Content',ctypes.c_char*501)# 消息正文
,('SequenceLabel',ctypes.c_char*2)# 经纪公司通知内容序列号
]
def __init__(self,BrokerID= '',Content='',SequenceLabel=''):
super(NoticeField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.Content=self._to_bytes(Content)
self.SequenceLabel=self._to_bytes(SequenceLabel)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.Content=self._to_bytes(i_tuple[2])
self.SequenceLabel=self._to_bytes(i_tuple[3])
class UserRightField(Base):
"""用户权限"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('UserRightType',ctypes.c_char)# 客户权限类型
,('IsForbidden',ctypes.c_int)# 是否禁止
]
def __init__(self,BrokerID= '',UserID='',UserRightType='',IsForbidden=0):
super(UserRightField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.UserRightType=self._to_bytes(UserRightType)
self.IsForbidden=int(IsForbidden)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
self.UserRightType=self._to_bytes(i_tuple[3])
self.IsForbidden=int(i_tuple[4])
class QrySettlementInfoConfirmField(Base):
"""查询结算信息确认域"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('CurrencyID',ctypes.c_char*4)# 币种代码
]
def __init__(self,BrokerID= '',InvestorID='',AccountID='',CurrencyID=''):
super(QrySettlementInfoConfirmField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.AccountID=self._to_bytes(i_tuple[3])
self.CurrencyID=self._to_bytes(i_tuple[4])
class LoadSettlementInfoField(Base):
"""装载结算信息"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
]
def __init__(self,BrokerID= ''):
super(LoadSettlementInfoField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
class BrokerWithdrawAlgorithmField(Base):
"""经纪公司可提资金算法表"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('WithdrawAlgorithm',ctypes.c_char)# 可提资金算法
,('UsingRatio',ctypes.c_double)# 资金使用率
,('IncludeCloseProfit',ctypes.c_char)# 可提是否包含平仓盈利
,('AllWithoutTrade',ctypes.c_char)# 本日无仓且无成交客户是否受可提比例限制
,('AvailIncludeCloseProfit',ctypes.c_char)# 可用是否包含平仓盈利
,('IsBrokerUserEvent',ctypes.c_int)# 是否启用用户事件
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('FundMortgageRatio',ctypes.c_double)# 货币质押比率
,('BalanceAlgorithm',ctypes.c_char)# 权益算法
]
def __init__(self,BrokerID= '',WithdrawAlgorithm='',UsingRatio=0.0,IncludeCloseProfit='',AllWithoutTrade='',AvailIncludeCloseProfit='',IsBrokerUserEvent=0,CurrencyID='',FundMortgageRatio=0.0,BalanceAlgorithm=''):
super(BrokerWithdrawAlgorithmField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.WithdrawAlgorithm=self._to_bytes(WithdrawAlgorithm)
self.UsingRatio=float(UsingRatio)
self.IncludeCloseProfit=self._to_bytes(IncludeCloseProfit)
self.AllWithoutTrade=self._to_bytes(AllWithoutTrade)
self.AvailIncludeCloseProfit=self._to_bytes(AvailIncludeCloseProfit)
self.IsBrokerUserEvent=int(IsBrokerUserEvent)
self.CurrencyID=self._to_bytes(CurrencyID)
self.FundMortgageRatio=float(FundMortgageRatio)
self.BalanceAlgorithm=self._to_bytes(BalanceAlgorithm)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.WithdrawAlgorithm=self._to_bytes(i_tuple[2])
self.UsingRatio=float(i_tuple[3])
self.IncludeCloseProfit=self._to_bytes(i_tuple[4])
self.AllWithoutTrade=self._to_bytes(i_tuple[5])
self.AvailIncludeCloseProfit=self._to_bytes(i_tuple[6])
self.IsBrokerUserEvent=int(i_tuple[7])
self.CurrencyID=self._to_bytes(i_tuple[8])
self.FundMortgageRatio=float(i_tuple[9])
self.BalanceAlgorithm=self._to_bytes(i_tuple[10])
class TradingAccountPasswordUpdateV1Field(Base):
"""资金账户口令变更域"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('OldPassword',ctypes.c_char*41)# 原来的口令
,('NewPassword',ctypes.c_char*41)# 新的口令
]
def __init__(self,BrokerID= '',InvestorID='',OldPassword='',NewPassword=''):
super(TradingAccountPasswordUpdateV1Field,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.OldPassword=self._to_bytes(OldPassword)
self.NewPassword=self._to_bytes(NewPassword)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.OldPassword=self._to_bytes(i_tuple[3])
self.NewPassword=self._to_bytes(i_tuple[4])
class TradingAccountPasswordUpdateField(Base):
"""资金账户口令变更域"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('OldPassword',ctypes.c_char*41)# 原来的口令
,('NewPassword',ctypes.c_char*41)# 新的口令
,('CurrencyID',ctypes.c_char*4)# 币种代码
]
def __init__(self,BrokerID= '',AccountID='',OldPassword='',NewPassword='',CurrencyID=''):
super(TradingAccountPasswordUpdateField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.AccountID=self._to_bytes(AccountID)
self.OldPassword=self._to_bytes(OldPassword)
self.NewPassword=self._to_bytes(NewPassword)
self.CurrencyID=self._to_bytes(CurrencyID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.AccountID=self._to_bytes(i_tuple[2])
self.OldPassword=self._to_bytes(i_tuple[3])
self.NewPassword=self._to_bytes(i_tuple[4])
self.CurrencyID=self._to_bytes(i_tuple[5])
class QryCombinationLegField(Base):
"""查询组合合约分腿"""
_fields_ = [
('CombInstrumentID',ctypes.c_char*31)# ///组合合约代码
,('LegID',ctypes.c_int)# 单腿编号
,('LegInstrumentID',ctypes.c_char*31)# 单腿合约代码
]
def __init__(self,CombInstrumentID= '',LegID=0,LegInstrumentID=''):
super(QryCombinationLegField,self).__init__()
self.CombInstrumentID=self._to_bytes(CombInstrumentID)
self.LegID=int(LegID)
self.LegInstrumentID=self._to_bytes(LegInstrumentID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.CombInstrumentID=self._to_bytes(i_tuple[1])
self.LegID=int(i_tuple[2])
self.LegInstrumentID=self._to_bytes(i_tuple[3])
class QrySyncStatusField(Base):
"""查询组合合约分腿"""
_fields_ = [
('TradingDay',ctypes.c_char*9)# ///交易日
]
def __init__(self,TradingDay= ''):
super(QrySyncStatusField,self).__init__()
self.TradingDay=self._to_bytes(TradingDay)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradingDay=self._to_bytes(i_tuple[1])
class CombinationLegField(Base):
"""组合交易合约的单腿"""
_fields_ = [
('CombInstrumentID',ctypes.c_char*31)# ///组合合约代码
,('LegID',ctypes.c_int)# 单腿编号
,('LegInstrumentID',ctypes.c_char*31)# 单腿合约代码
,('Direction',ctypes.c_char)# 买卖方向
,('LegMultiple',ctypes.c_int)# 单腿乘数
,('ImplyLevel',ctypes.c_int)# 派生层数
]
def __init__(self,CombInstrumentID= '',LegID=0,LegInstrumentID='',Direction='',LegMultiple=0,ImplyLevel=0):
super(CombinationLegField,self).__init__()
self.CombInstrumentID=self._to_bytes(CombInstrumentID)
self.LegID=int(LegID)
self.LegInstrumentID=self._to_bytes(LegInstrumentID)
self.Direction=self._to_bytes(Direction)
self.LegMultiple=int(LegMultiple)
self.ImplyLevel=int(ImplyLevel)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.CombInstrumentID=self._to_bytes(i_tuple[1])
self.LegID=int(i_tuple[2])
self.LegInstrumentID=self._to_bytes(i_tuple[3])
self.Direction=self._to_bytes(i_tuple[4])
self.LegMultiple=int(i_tuple[5])
self.ImplyLevel=int(i_tuple[6])
class SyncStatusField(Base):
"""数据同步状态"""
_fields_ = [
('TradingDay',ctypes.c_char*9)# ///交易日
,('DataSyncStatus',ctypes.c_char)# 数据同步状态
]
def __init__(self,TradingDay= '',DataSyncStatus=''):
super(SyncStatusField,self).__init__()
self.TradingDay=self._to_bytes(TradingDay)
self.DataSyncStatus=self._to_bytes(DataSyncStatus)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradingDay=self._to_bytes(i_tuple[1])
self.DataSyncStatus=self._to_bytes(i_tuple[2])
class QryLinkManField(Base):
"""查询联系人"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
]
def __init__(self,BrokerID= '',InvestorID=''):
super(QryLinkManField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
class LinkManField(Base):
"""联系人"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('PersonType',ctypes.c_char)# 联系人类型
,('IdentifiedCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('PersonName',ctypes.c_char*81)# 名称
,('Telephone',ctypes.c_char*41)# 联系电话
,('Address',ctypes.c_char*101)# 通讯地址
,('ZipCode',ctypes.c_char*7)# 邮政编码
,('Priority',ctypes.c_int)# 优先级
,('UOAZipCode',ctypes.c_char*11)# 开户邮政编码
,('PersonFullName',ctypes.c_char*101)# 全称
]
def __init__(self,BrokerID= '',InvestorID='',PersonType='',IdentifiedCardType='',IdentifiedCardNo='',PersonName='',Telephone='',Address='',ZipCode='',Priority=0,UOAZipCode='',PersonFullName=''):
super(LinkManField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.PersonType=self._to_bytes(PersonType)
self.IdentifiedCardType=self._to_bytes(IdentifiedCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.PersonName=self._to_bytes(PersonName)
self.Telephone=self._to_bytes(Telephone)
self.Address=self._to_bytes(Address)
self.ZipCode=self._to_bytes(ZipCode)
self.Priority=int(Priority)
self.UOAZipCode=self._to_bytes(UOAZipCode)
self.PersonFullName=self._to_bytes(PersonFullName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.PersonType=self._to_bytes(i_tuple[3])
self.IdentifiedCardType=self._to_bytes(i_tuple[4])
self.IdentifiedCardNo=self._to_bytes(i_tuple[5])
self.PersonName=self._to_bytes(i_tuple[6])
self.Telephone=self._to_bytes(i_tuple[7])
self.Address=self._to_bytes(i_tuple[8])
self.ZipCode=self._to_bytes(i_tuple[9])
self.Priority=int(i_tuple[10])
self.UOAZipCode=self._to_bytes(i_tuple[11])
self.PersonFullName=self._to_bytes(i_tuple[12])
class QryBrokerUserEventField(Base):
"""查询经纪公司用户事件"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('UserEventType',ctypes.c_char)# 用户事件类型
]
def __init__(self,BrokerID= '',UserID='',UserEventType=''):
super(QryBrokerUserEventField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.UserEventType=self._to_bytes(UserEventType)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
self.UserEventType=self._to_bytes(i_tuple[3])
class BrokerUserEventField(Base):
"""查询经纪公司用户事件"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('UserEventType',ctypes.c_char)# 用户事件类型
,('EventSequenceNo',ctypes.c_int)# 用户事件序号
,('EventDate',ctypes.c_char*9)# 事件发生日期
,('EventTime',ctypes.c_char*9)# 事件发生时间
,('UserEventInfo',ctypes.c_char*1025)# 用户事件信息
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
]
def __init__(self,BrokerID= '',UserID='',UserEventType='',EventSequenceNo=0,EventDate='',EventTime='',UserEventInfo='',InvestorID='',InstrumentID=''):
super(BrokerUserEventField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.UserEventType=self._to_bytes(UserEventType)
self.EventSequenceNo=int(EventSequenceNo)
self.EventDate=self._to_bytes(EventDate)
self.EventTime=self._to_bytes(EventTime)
self.UserEventInfo=self._to_bytes(UserEventInfo)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
self.UserEventType=self._to_bytes(i_tuple[3])
self.EventSequenceNo=int(i_tuple[4])
self.EventDate=self._to_bytes(i_tuple[5])
self.EventTime=self._to_bytes(i_tuple[6])
self.UserEventInfo=self._to_bytes(i_tuple[7])
self.InvestorID=self._to_bytes(i_tuple[8])
self.InstrumentID=self._to_bytes(i_tuple[9])
class QryContractBankField(Base):
"""查询签约银行请求"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBrchID',ctypes.c_char*5)# 银行分中心代码
]
def __init__(self,BrokerID= '',BankID='',BankBrchID=''):
super(QryContractBankField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.BankID=self._to_bytes(BankID)
self.BankBrchID=self._to_bytes(BankBrchID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBrchID=self._to_bytes(i_tuple[3])
class ContractBankField(Base):
"""查询签约银行响应"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBrchID',ctypes.c_char*5)# 银行分中心代码
,('BankName',ctypes.c_char*101)# 银行名称
]
def __init__(self,BrokerID= '',BankID='',BankBrchID='',BankName=''):
super(ContractBankField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.BankID=self._to_bytes(BankID)
self.BankBrchID=self._to_bytes(BankBrchID)
self.BankName=self._to_bytes(BankName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBrchID=self._to_bytes(i_tuple[3])
self.BankName=self._to_bytes(i_tuple[4])
class InvestorPositionCombineDetailField(Base):
"""投资者组合持仓明细"""
_fields_ = [
('TradingDay',ctypes.c_char*9)# ///交易日
,('OpenDate',ctypes.c_char*9)# 开仓日期
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('SettlementID',ctypes.c_int)# 结算编号
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('ComTradeID',ctypes.c_char*21)# 组合编号
,('TradeID',ctypes.c_char*21)# 撮合编号
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('Direction',ctypes.c_char)# 买卖
,('TotalAmt',ctypes.c_int)# 持仓量
,('Margin',ctypes.c_double)# 投资者保证金
,('ExchMargin',ctypes.c_double)# 交易所保证金
,('MarginRateByMoney',ctypes.c_double)# 保证金率
,('MarginRateByVolume',ctypes.c_double)# 保证金率(按手数)
,('LegID',ctypes.c_int)# 单腿编号
,('LegMultiple',ctypes.c_int)# 单腿乘数
,('CombInstrumentID',ctypes.c_char*31)# 组合持仓合约编码
,('TradeGroupID',ctypes.c_int)# 成交组号
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,TradingDay= '',OpenDate='',ExchangeID='',SettlementID=0,BrokerID='',InvestorID='',ComTradeID='',TradeID='',InstrumentID='',HedgeFlag='',Direction='',TotalAmt=0,Margin=0.0,ExchMargin=0.0,MarginRateByMoney=0.0,MarginRateByVolume=0.0,LegID=0,LegMultiple=0,CombInstrumentID='',TradeGroupID=0,InvestUnitID=''):
super(InvestorPositionCombineDetailField,self).__init__()
self.TradingDay=self._to_bytes(TradingDay)
self.OpenDate=self._to_bytes(OpenDate)
self.ExchangeID=self._to_bytes(ExchangeID)
self.SettlementID=int(SettlementID)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.ComTradeID=self._to_bytes(ComTradeID)
self.TradeID=self._to_bytes(TradeID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.Direction=self._to_bytes(Direction)
self.TotalAmt=int(TotalAmt)
self.Margin=float(Margin)
self.ExchMargin=float(ExchMargin)
self.MarginRateByMoney=float(MarginRateByMoney)
self.MarginRateByVolume=float(MarginRateByVolume)
self.LegID=int(LegID)
self.LegMultiple=int(LegMultiple)
self.CombInstrumentID=self._to_bytes(CombInstrumentID)
self.TradeGroupID=int(TradeGroupID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradingDay=self._to_bytes(i_tuple[1])
self.OpenDate=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
self.SettlementID=int(i_tuple[4])
self.BrokerID=self._to_bytes(i_tuple[5])
self.InvestorID=self._to_bytes(i_tuple[6])
self.ComTradeID=self._to_bytes(i_tuple[7])
self.TradeID=self._to_bytes(i_tuple[8])
self.InstrumentID=self._to_bytes(i_tuple[9])
self.HedgeFlag=self._to_bytes(i_tuple[10])
self.Direction=self._to_bytes(i_tuple[11])
self.TotalAmt=int(i_tuple[12])
self.Margin=float(i_tuple[13])
self.ExchMargin=float(i_tuple[14])
self.MarginRateByMoney=float(i_tuple[15])
self.MarginRateByVolume=float(i_tuple[16])
self.LegID=int(i_tuple[17])
self.LegMultiple=int(i_tuple[18])
self.CombInstrumentID=self._to_bytes(i_tuple[19])
self.TradeGroupID=int(i_tuple[20])
self.InvestUnitID=self._to_bytes(i_tuple[21])
class ParkedOrderField(Base):
"""预埋单"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('OrderRef',ctypes.c_char*13)# 报单引用
,('UserID',ctypes.c_char*16)# 用户代码
,('OrderPriceType',ctypes.c_char)# 报单价格条件
,('Direction',ctypes.c_char)# 买卖方向
,('CombOffsetFlag',ctypes.c_char*5)# 组合开平标志
,('CombHedgeFlag',ctypes.c_char*5)# 组合投机套保标志
,('LimitPrice',ctypes.c_double)# 价格
,('VolumeTotalOriginal',ctypes.c_int)# 数量
,('TimeCondition',ctypes.c_char)# 有效期类型
,('GTDDate',ctypes.c_char*9)# GTD日期
,('VolumeCondition',ctypes.c_char)# 成交量类型
,('MinVolume',ctypes.c_int)# 最小成交量
,('ContingentCondition',ctypes.c_char)# 触发条件
,('StopPrice',ctypes.c_double)# 止损价
,('ForceCloseReason',ctypes.c_char)# 强平原因
,('IsAutoSuspend',ctypes.c_int)# 自动挂起标志
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('RequestID',ctypes.c_int)# 请求编号
,('UserForceClose',ctypes.c_int)# 用户强评标志
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ParkedOrderID',ctypes.c_char*13)# 预埋报单编号
,('UserType',ctypes.c_char)# 用户类型
,('Status',ctypes.c_char)# 预埋单状态
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
,('IsSwapOrder',ctypes.c_int)# 互换单标志
,('AccountID',ctypes.c_char*13)# 资金账号
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('ClientID',ctypes.c_char*11)# 交易编码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',OrderRef='',UserID='',OrderPriceType='',Direction='',CombOffsetFlag='',CombHedgeFlag='',LimitPrice=0.0,VolumeTotalOriginal=0,TimeCondition='',GTDDate='',VolumeCondition='',MinVolume=0,ContingentCondition='',StopPrice=0.0,ForceCloseReason='',IsAutoSuspend=0,BusinessUnit='',RequestID=0,UserForceClose=0,ExchangeID='',ParkedOrderID='',UserType='',Status='',ErrorID=0,ErrorMsg='',IsSwapOrder=0,AccountID='',CurrencyID='',ClientID='',InvestUnitID='',IPAddress='',MacAddress=''):
super(ParkedOrderField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.OrderRef=self._to_bytes(OrderRef)
self.UserID=self._to_bytes(UserID)
self.OrderPriceType=self._to_bytes(OrderPriceType)
self.Direction=self._to_bytes(Direction)
self.CombOffsetFlag=self._to_bytes(CombOffsetFlag)
self.CombHedgeFlag=self._to_bytes(CombHedgeFlag)
self.LimitPrice=float(LimitPrice)
self.VolumeTotalOriginal=int(VolumeTotalOriginal)
self.TimeCondition=self._to_bytes(TimeCondition)
self.GTDDate=self._to_bytes(GTDDate)
self.VolumeCondition=self._to_bytes(VolumeCondition)
self.MinVolume=int(MinVolume)
self.ContingentCondition=self._to_bytes(ContingentCondition)
self.StopPrice=float(StopPrice)
self.ForceCloseReason=self._to_bytes(ForceCloseReason)
self.IsAutoSuspend=int(IsAutoSuspend)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.RequestID=int(RequestID)
self.UserForceClose=int(UserForceClose)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParkedOrderID=self._to_bytes(ParkedOrderID)
self.UserType=self._to_bytes(UserType)
self.Status=self._to_bytes(Status)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
self.IsSwapOrder=int(IsSwapOrder)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
self.ClientID=self._to_bytes(ClientID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.OrderRef=self._to_bytes(i_tuple[4])
self.UserID=self._to_bytes(i_tuple[5])
self.OrderPriceType=self._to_bytes(i_tuple[6])
self.Direction=self._to_bytes(i_tuple[7])
self.CombOffsetFlag=self._to_bytes(i_tuple[8])
self.CombHedgeFlag=self._to_bytes(i_tuple[9])
self.LimitPrice=float(i_tuple[10])
self.VolumeTotalOriginal=int(i_tuple[11])
self.TimeCondition=self._to_bytes(i_tuple[12])
self.GTDDate=self._to_bytes(i_tuple[13])
self.VolumeCondition=self._to_bytes(i_tuple[14])
self.MinVolume=int(i_tuple[15])
self.ContingentCondition=self._to_bytes(i_tuple[16])
self.StopPrice=float(i_tuple[17])
self.ForceCloseReason=self._to_bytes(i_tuple[18])
self.IsAutoSuspend=int(i_tuple[19])
self.BusinessUnit=self._to_bytes(i_tuple[20])
self.RequestID=int(i_tuple[21])
self.UserForceClose=int(i_tuple[22])
self.ExchangeID=self._to_bytes(i_tuple[23])
self.ParkedOrderID=self._to_bytes(i_tuple[24])
self.UserType=self._to_bytes(i_tuple[25])
self.Status=self._to_bytes(i_tuple[26])
self.ErrorID=int(i_tuple[27])
self.ErrorMsg=self._to_bytes(i_tuple[28])
self.IsSwapOrder=int(i_tuple[29])
self.AccountID=self._to_bytes(i_tuple[30])
self.CurrencyID=self._to_bytes(i_tuple[31])
self.ClientID=self._to_bytes(i_tuple[32])
self.InvestUnitID=self._to_bytes(i_tuple[33])
self.IPAddress=self._to_bytes(i_tuple[34])
self.MacAddress=self._to_bytes(i_tuple[35])
class ParkedOrderActionField(Base):
"""输入预埋单操作"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('OrderActionRef',ctypes.c_int)# 报单操作引用
,('OrderRef',ctypes.c_char*13)# 报单引用
,('RequestID',ctypes.c_int)# 请求编号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('OrderSysID',ctypes.c_char*21)# 报单编号
,('ActionFlag',ctypes.c_char)# 操作标志
,('LimitPrice',ctypes.c_double)# 价格
,('VolumeChange',ctypes.c_int)# 数量变化
,('UserID',ctypes.c_char*16)# 用户代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ParkedOrderActionID',ctypes.c_char*13)# 预埋撤单单编号
,('UserType',ctypes.c_char)# 用户类型
,('Status',ctypes.c_char)# 预埋撤单状态
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',OrderActionRef=0,OrderRef='',RequestID=0,FrontID=0,SessionID=0,ExchangeID='',OrderSysID='',ActionFlag='',LimitPrice=0.0,VolumeChange=0,UserID='',InstrumentID='',ParkedOrderActionID='',UserType='',Status='',ErrorID=0,ErrorMsg='',InvestUnitID='',IPAddress='',MacAddress=''):
super(ParkedOrderActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.OrderActionRef=int(OrderActionRef)
self.OrderRef=self._to_bytes(OrderRef)
self.RequestID=int(RequestID)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.OrderSysID=self._to_bytes(OrderSysID)
self.ActionFlag=self._to_bytes(ActionFlag)
self.LimitPrice=float(LimitPrice)
self.VolumeChange=int(VolumeChange)
self.UserID=self._to_bytes(UserID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ParkedOrderActionID=self._to_bytes(ParkedOrderActionID)
self.UserType=self._to_bytes(UserType)
self.Status=self._to_bytes(Status)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.OrderActionRef=int(i_tuple[3])
self.OrderRef=self._to_bytes(i_tuple[4])
self.RequestID=int(i_tuple[5])
self.FrontID=int(i_tuple[6])
self.SessionID=int(i_tuple[7])
self.ExchangeID=self._to_bytes(i_tuple[8])
self.OrderSysID=self._to_bytes(i_tuple[9])
self.ActionFlag=self._to_bytes(i_tuple[10])
self.LimitPrice=float(i_tuple[11])
self.VolumeChange=int(i_tuple[12])
self.UserID=self._to_bytes(i_tuple[13])
self.InstrumentID=self._to_bytes(i_tuple[14])
self.ParkedOrderActionID=self._to_bytes(i_tuple[15])
self.UserType=self._to_bytes(i_tuple[16])
self.Status=self._to_bytes(i_tuple[17])
self.ErrorID=int(i_tuple[18])
self.ErrorMsg=self._to_bytes(i_tuple[19])
self.InvestUnitID=self._to_bytes(i_tuple[20])
self.IPAddress=self._to_bytes(i_tuple[21])
self.MacAddress=self._to_bytes(i_tuple[22])
class QryParkedOrderField(Base):
"""查询预埋单"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ExchangeID='',InvestUnitID=''):
super(QryParkedOrderField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.InvestUnitID=self._to_bytes(i_tuple[5])
class QryParkedOrderActionField(Base):
"""查询预埋撤单"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',ExchangeID='',InvestUnitID=''):
super(QryParkedOrderActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.InvestUnitID=self._to_bytes(i_tuple[5])
class RemoveParkedOrderField(Base):
"""删除预埋单"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('ParkedOrderID',ctypes.c_char*13)# 预埋报单编号
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',ParkedOrderID='',InvestUnitID=''):
super(RemoveParkedOrderField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.ParkedOrderID=self._to_bytes(ParkedOrderID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.ParkedOrderID=self._to_bytes(i_tuple[3])
self.InvestUnitID=self._to_bytes(i_tuple[4])
class RemoveParkedOrderActionField(Base):
"""删除预埋撤单"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('ParkedOrderActionID',ctypes.c_char*13)# 预埋撤单编号
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',ParkedOrderActionID='',InvestUnitID=''):
super(RemoveParkedOrderActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.ParkedOrderActionID=self._to_bytes(ParkedOrderActionID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.ParkedOrderActionID=self._to_bytes(i_tuple[3])
self.InvestUnitID=self._to_bytes(i_tuple[4])
class InvestorWithdrawAlgorithmField(Base):
"""经纪公司可提资金算法表"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('UsingRatio',ctypes.c_double)# 可提资金比例
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('FundMortgageRatio',ctypes.c_double)# 货币质押比率
]
def __init__(self,BrokerID= '',InvestorRange='',InvestorID='',UsingRatio=0.0,CurrencyID='',FundMortgageRatio=0.0):
super(InvestorWithdrawAlgorithmField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.InvestorID=self._to_bytes(InvestorID)
self.UsingRatio=float(UsingRatio)
self.CurrencyID=self._to_bytes(CurrencyID)
self.FundMortgageRatio=float(FundMortgageRatio)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.InvestorID=self._to_bytes(i_tuple[3])
self.UsingRatio=float(i_tuple[4])
self.CurrencyID=self._to_bytes(i_tuple[5])
self.FundMortgageRatio=float(i_tuple[6])
class QryInvestorPositionCombineDetailField(Base):
"""查询组合持仓明细"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('CombInstrumentID',ctypes.c_char*31)# 组合持仓合约编码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',CombInstrumentID='',ExchangeID='',InvestUnitID=''):
super(QryInvestorPositionCombineDetailField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.CombInstrumentID=self._to_bytes(CombInstrumentID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.CombInstrumentID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.InvestUnitID=self._to_bytes(i_tuple[5])
class MarketDataAveragePriceField(Base):
"""成交均价"""
_fields_ = [
('AveragePrice',ctypes.c_double)# ///当日均价
]
def __init__(self,AveragePrice= 0.0):
super(MarketDataAveragePriceField,self).__init__()
self.AveragePrice=float(AveragePrice)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.AveragePrice=float(i_tuple[1])
class VerifyInvestorPasswordField(Base):
"""校验投资者密码"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('Password',ctypes.c_char*41)# 密码
]
def __init__(self,BrokerID= '',InvestorID='',Password=''):
super(VerifyInvestorPasswordField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.Password=self._to_bytes(Password)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.Password=self._to_bytes(i_tuple[3])
class UserIPField(Base):
"""用户IP"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('IPMask',ctypes.c_char*16)# IP地址掩码
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',UserID='',IPAddress='',IPMask='',MacAddress=''):
super(UserIPField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.IPAddress=self._to_bytes(IPAddress)
self.IPMask=self._to_bytes(IPMask)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
self.IPAddress=self._to_bytes(i_tuple[3])
self.IPMask=self._to_bytes(i_tuple[4])
self.MacAddress=self._to_bytes(i_tuple[5])
class TradingNoticeInfoField(Base):
"""用户事件通知信息"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('SendTime',ctypes.c_char*9)# 发送时间
,('FieldContent',ctypes.c_char*501)# 消息正文
,('SequenceSeries',ctypes.c_short)# 序列系列号
,('SequenceNo',ctypes.c_int)# 序列号
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',SendTime='',FieldContent='',SequenceSeries=0,SequenceNo=0,InvestUnitID=''):
super(TradingNoticeInfoField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.SendTime=self._to_bytes(SendTime)
self.FieldContent=self._to_bytes(FieldContent)
self.SequenceSeries=int(SequenceSeries)
self.SequenceNo=int(SequenceNo)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.SendTime=self._to_bytes(i_tuple[3])
self.FieldContent=self._to_bytes(i_tuple[4])
self.SequenceSeries=int(i_tuple[5])
self.SequenceNo=int(i_tuple[6])
self.InvestUnitID=self._to_bytes(i_tuple[7])
class TradingNoticeField(Base):
"""用户事件通知"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorRange',ctypes.c_char)# 投资者范围
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('SequenceSeries',ctypes.c_short)# 序列系列号
,('UserID',ctypes.c_char*16)# 用户代码
,('SendTime',ctypes.c_char*9)# 发送时间
,('SequenceNo',ctypes.c_int)# 序列号
,('FieldContent',ctypes.c_char*501)# 消息正文
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorRange='',InvestorID='',SequenceSeries=0,UserID='',SendTime='',SequenceNo=0,FieldContent='',InvestUnitID=''):
super(TradingNoticeField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorRange=self._to_bytes(InvestorRange)
self.InvestorID=self._to_bytes(InvestorID)
self.SequenceSeries=int(SequenceSeries)
self.UserID=self._to_bytes(UserID)
self.SendTime=self._to_bytes(SendTime)
self.SequenceNo=int(SequenceNo)
self.FieldContent=self._to_bytes(FieldContent)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorRange=self._to_bytes(i_tuple[2])
self.InvestorID=self._to_bytes(i_tuple[3])
self.SequenceSeries=int(i_tuple[4])
self.UserID=self._to_bytes(i_tuple[5])
self.SendTime=self._to_bytes(i_tuple[6])
self.SequenceNo=int(i_tuple[7])
self.FieldContent=self._to_bytes(i_tuple[8])
self.InvestUnitID=self._to_bytes(i_tuple[9])
class QryTradingNoticeField(Base):
"""查询交易事件通知"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InvestUnitID=''):
super(QryTradingNoticeField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InvestUnitID=self._to_bytes(i_tuple[3])
class QryErrOrderField(Base):
"""查询错误报单"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
]
def __init__(self,BrokerID= '',InvestorID=''):
super(QryErrOrderField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
class ErrOrderField(Base):
"""错误报单"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('OrderRef',ctypes.c_char*13)# 报单引用
,('UserID',ctypes.c_char*16)# 用户代码
,('OrderPriceType',ctypes.c_char)# 报单价格条件
,('Direction',ctypes.c_char)# 买卖方向
,('CombOffsetFlag',ctypes.c_char*5)# 组合开平标志
,('CombHedgeFlag',ctypes.c_char*5)# 组合投机套保标志
,('LimitPrice',ctypes.c_double)# 价格
,('VolumeTotalOriginal',ctypes.c_int)# 数量
,('TimeCondition',ctypes.c_char)# 有效期类型
,('GTDDate',ctypes.c_char*9)# GTD日期
,('VolumeCondition',ctypes.c_char)# 成交量类型
,('MinVolume',ctypes.c_int)# 最小成交量
,('ContingentCondition',ctypes.c_char)# 触发条件
,('StopPrice',ctypes.c_double)# 止损价
,('ForceCloseReason',ctypes.c_char)# 强平原因
,('IsAutoSuspend',ctypes.c_int)# 自动挂起标志
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('RequestID',ctypes.c_int)# 请求编号
,('UserForceClose',ctypes.c_int)# 用户强评标志
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
,('IsSwapOrder',ctypes.c_int)# 互换单标志
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('AccountID',ctypes.c_char*13)# 资金账号
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('ClientID',ctypes.c_char*11)# 交易编码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',OrderRef='',UserID='',OrderPriceType='',Direction='',CombOffsetFlag='',CombHedgeFlag='',LimitPrice=0.0,VolumeTotalOriginal=0,TimeCondition='',GTDDate='',VolumeCondition='',MinVolume=0,ContingentCondition='',StopPrice=0.0,ForceCloseReason='',IsAutoSuspend=0,BusinessUnit='',RequestID=0,UserForceClose=0,ErrorID=0,ErrorMsg='',IsSwapOrder=0,ExchangeID='',InvestUnitID='',AccountID='',CurrencyID='',ClientID='',IPAddress='',MacAddress=''):
super(ErrOrderField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.OrderRef=self._to_bytes(OrderRef)
self.UserID=self._to_bytes(UserID)
self.OrderPriceType=self._to_bytes(OrderPriceType)
self.Direction=self._to_bytes(Direction)
self.CombOffsetFlag=self._to_bytes(CombOffsetFlag)
self.CombHedgeFlag=self._to_bytes(CombHedgeFlag)
self.LimitPrice=float(LimitPrice)
self.VolumeTotalOriginal=int(VolumeTotalOriginal)
self.TimeCondition=self._to_bytes(TimeCondition)
self.GTDDate=self._to_bytes(GTDDate)
self.VolumeCondition=self._to_bytes(VolumeCondition)
self.MinVolume=int(MinVolume)
self.ContingentCondition=self._to_bytes(ContingentCondition)
self.StopPrice=float(StopPrice)
self.ForceCloseReason=self._to_bytes(ForceCloseReason)
self.IsAutoSuspend=int(IsAutoSuspend)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.RequestID=int(RequestID)
self.UserForceClose=int(UserForceClose)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
self.IsSwapOrder=int(IsSwapOrder)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
self.ClientID=self._to_bytes(ClientID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.OrderRef=self._to_bytes(i_tuple[4])
self.UserID=self._to_bytes(i_tuple[5])
self.OrderPriceType=self._to_bytes(i_tuple[6])
self.Direction=self._to_bytes(i_tuple[7])
self.CombOffsetFlag=self._to_bytes(i_tuple[8])
self.CombHedgeFlag=self._to_bytes(i_tuple[9])
self.LimitPrice=float(i_tuple[10])
self.VolumeTotalOriginal=int(i_tuple[11])
self.TimeCondition=self._to_bytes(i_tuple[12])
self.GTDDate=self._to_bytes(i_tuple[13])
self.VolumeCondition=self._to_bytes(i_tuple[14])
self.MinVolume=int(i_tuple[15])
self.ContingentCondition=self._to_bytes(i_tuple[16])
self.StopPrice=float(i_tuple[17])
self.ForceCloseReason=self._to_bytes(i_tuple[18])
self.IsAutoSuspend=int(i_tuple[19])
self.BusinessUnit=self._to_bytes(i_tuple[20])
self.RequestID=int(i_tuple[21])
self.UserForceClose=int(i_tuple[22])
self.ErrorID=int(i_tuple[23])
self.ErrorMsg=self._to_bytes(i_tuple[24])
self.IsSwapOrder=int(i_tuple[25])
self.ExchangeID=self._to_bytes(i_tuple[26])
self.InvestUnitID=self._to_bytes(i_tuple[27])
self.AccountID=self._to_bytes(i_tuple[28])
self.CurrencyID=self._to_bytes(i_tuple[29])
self.ClientID=self._to_bytes(i_tuple[30])
self.IPAddress=self._to_bytes(i_tuple[31])
self.MacAddress=self._to_bytes(i_tuple[32])
class ErrorConditionalOrderField(Base):
"""查询错误报单操作"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('OrderRef',ctypes.c_char*13)# 报单引用
,('UserID',ctypes.c_char*16)# 用户代码
,('OrderPriceType',ctypes.c_char)# 报单价格条件
,('Direction',ctypes.c_char)# 买卖方向
,('CombOffsetFlag',ctypes.c_char*5)# 组合开平标志
,('CombHedgeFlag',ctypes.c_char*5)# 组合投机套保标志
,('LimitPrice',ctypes.c_double)# 价格
,('VolumeTotalOriginal',ctypes.c_int)# 数量
,('TimeCondition',ctypes.c_char)# 有效期类型
,('GTDDate',ctypes.c_char*9)# GTD日期
,('VolumeCondition',ctypes.c_char)# 成交量类型
,('MinVolume',ctypes.c_int)# 最小成交量
,('ContingentCondition',ctypes.c_char)# 触发条件
,('StopPrice',ctypes.c_double)# 止损价
,('ForceCloseReason',ctypes.c_char)# 强平原因
,('IsAutoSuspend',ctypes.c_int)# 自动挂起标志
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('RequestID',ctypes.c_int)# 请求编号
,('OrderLocalID',ctypes.c_char*13)# 本地报单编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('ExchangeInstID',ctypes.c_char*31)# 合约在交易所的代码
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('OrderSubmitStatus',ctypes.c_char)# 报单提交状态
,('NotifySequence',ctypes.c_int)# 报单提示序号
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('OrderSysID',ctypes.c_char*21)# 报单编号
,('OrderSource',ctypes.c_char)# 报单来源
,('OrderStatus',ctypes.c_char)# 报单状态
,('OrderType',ctypes.c_char)# 报单类型
,('VolumeTraded',ctypes.c_int)# 今成交数量
,('VolumeTotal',ctypes.c_int)# 剩余数量
,('InsertDate',ctypes.c_char*9)# 报单日期
,('InsertTime',ctypes.c_char*9)# 委托时间
,('ActiveTime',ctypes.c_char*9)# 激活时间
,('SuspendTime',ctypes.c_char*9)# 挂起时间
,('UpdateTime',ctypes.c_char*9)# 最后修改时间
,('CancelTime',ctypes.c_char*9)# 撤销时间
,('ActiveTraderID',ctypes.c_char*21)# 最后修改交易所交易员代码
,('ClearingPartID',ctypes.c_char*11)# 结算会员编号
,('SequenceNo',ctypes.c_int)# 序号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('UserProductInfo',ctypes.c_char*11)# 用户端产品信息
,('StatusMsg',ctypes.c_char*81)# 状态信息
,('UserForceClose',ctypes.c_int)# 用户强评标志
,('ActiveUserID',ctypes.c_char*16)# 操作用户代码
,('BrokerOrderSeq',ctypes.c_int)# 经纪公司报单编号
,('RelativeOrderSysID',ctypes.c_char*21)# 相关报单
,('ZCETotalTradedVolume',ctypes.c_int)# 郑商所成交数量
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
,('IsSwapOrder',ctypes.c_int)# 互换单标志
,('BranchID',ctypes.c_char*9)# 营业部编号
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('AccountID',ctypes.c_char*13)# 资金账号
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',OrderRef='',UserID='',OrderPriceType='',Direction='',CombOffsetFlag='',CombHedgeFlag='',LimitPrice=0.0,VolumeTotalOriginal=0,TimeCondition='',GTDDate='',VolumeCondition='',MinVolume=0,ContingentCondition='',StopPrice=0.0,ForceCloseReason='',IsAutoSuspend=0,BusinessUnit='',RequestID=0,OrderLocalID='',ExchangeID='',ParticipantID='',ClientID='',ExchangeInstID='',TraderID='',InstallID=0,OrderSubmitStatus='',NotifySequence=0,TradingDay='',SettlementID=0,OrderSysID='',OrderSource='',OrderStatus='',OrderType='',VolumeTraded=0,VolumeTotal=0,InsertDate='',InsertTime='',ActiveTime='',SuspendTime='',UpdateTime='',CancelTime='',ActiveTraderID='',ClearingPartID='',SequenceNo=0,FrontID=0,SessionID=0,UserProductInfo='',StatusMsg='',UserForceClose=0,ActiveUserID='',BrokerOrderSeq=0,RelativeOrderSysID='',ZCETotalTradedVolume=0,ErrorID=0,ErrorMsg='',IsSwapOrder=0,BranchID='',InvestUnitID='',AccountID='',CurrencyID='',IPAddress='',MacAddress=''):
super(ErrorConditionalOrderField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.OrderRef=self._to_bytes(OrderRef)
self.UserID=self._to_bytes(UserID)
self.OrderPriceType=self._to_bytes(OrderPriceType)
self.Direction=self._to_bytes(Direction)
self.CombOffsetFlag=self._to_bytes(CombOffsetFlag)
self.CombHedgeFlag=self._to_bytes(CombHedgeFlag)
self.LimitPrice=float(LimitPrice)
self.VolumeTotalOriginal=int(VolumeTotalOriginal)
self.TimeCondition=self._to_bytes(TimeCondition)
self.GTDDate=self._to_bytes(GTDDate)
self.VolumeCondition=self._to_bytes(VolumeCondition)
self.MinVolume=int(MinVolume)
self.ContingentCondition=self._to_bytes(ContingentCondition)
self.StopPrice=float(StopPrice)
self.ForceCloseReason=self._to_bytes(ForceCloseReason)
self.IsAutoSuspend=int(IsAutoSuspend)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.RequestID=int(RequestID)
self.OrderLocalID=self._to_bytes(OrderLocalID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.ExchangeInstID=self._to_bytes(ExchangeInstID)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.OrderSubmitStatus=self._to_bytes(OrderSubmitStatus)
self.NotifySequence=int(NotifySequence)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.OrderSysID=self._to_bytes(OrderSysID)
self.OrderSource=self._to_bytes(OrderSource)
self.OrderStatus=self._to_bytes(OrderStatus)
self.OrderType=self._to_bytes(OrderType)
self.VolumeTraded=int(VolumeTraded)
self.VolumeTotal=int(VolumeTotal)
self.InsertDate=self._to_bytes(InsertDate)
self.InsertTime=self._to_bytes(InsertTime)
self.ActiveTime=self._to_bytes(ActiveTime)
self.SuspendTime=self._to_bytes(SuspendTime)
self.UpdateTime=self._to_bytes(UpdateTime)
self.CancelTime=self._to_bytes(CancelTime)
self.ActiveTraderID=self._to_bytes(ActiveTraderID)
self.ClearingPartID=self._to_bytes(ClearingPartID)
self.SequenceNo=int(SequenceNo)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.UserProductInfo=self._to_bytes(UserProductInfo)
self.StatusMsg=self._to_bytes(StatusMsg)
self.UserForceClose=int(UserForceClose)
self.ActiveUserID=self._to_bytes(ActiveUserID)
self.BrokerOrderSeq=int(BrokerOrderSeq)
self.RelativeOrderSysID=self._to_bytes(RelativeOrderSysID)
self.ZCETotalTradedVolume=int(ZCETotalTradedVolume)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
self.IsSwapOrder=int(IsSwapOrder)
self.BranchID=self._to_bytes(BranchID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.OrderRef=self._to_bytes(i_tuple[4])
self.UserID=self._to_bytes(i_tuple[5])
self.OrderPriceType=self._to_bytes(i_tuple[6])
self.Direction=self._to_bytes(i_tuple[7])
self.CombOffsetFlag=self._to_bytes(i_tuple[8])
self.CombHedgeFlag=self._to_bytes(i_tuple[9])
self.LimitPrice=float(i_tuple[10])
self.VolumeTotalOriginal=int(i_tuple[11])
self.TimeCondition=self._to_bytes(i_tuple[12])
self.GTDDate=self._to_bytes(i_tuple[13])
self.VolumeCondition=self._to_bytes(i_tuple[14])
self.MinVolume=int(i_tuple[15])
self.ContingentCondition=self._to_bytes(i_tuple[16])
self.StopPrice=float(i_tuple[17])
self.ForceCloseReason=self._to_bytes(i_tuple[18])
self.IsAutoSuspend=int(i_tuple[19])
self.BusinessUnit=self._to_bytes(i_tuple[20])
self.RequestID=int(i_tuple[21])
self.OrderLocalID=self._to_bytes(i_tuple[22])
self.ExchangeID=self._to_bytes(i_tuple[23])
self.ParticipantID=self._to_bytes(i_tuple[24])
self.ClientID=self._to_bytes(i_tuple[25])
self.ExchangeInstID=self._to_bytes(i_tuple[26])
self.TraderID=self._to_bytes(i_tuple[27])
self.InstallID=int(i_tuple[28])
self.OrderSubmitStatus=self._to_bytes(i_tuple[29])
self.NotifySequence=int(i_tuple[30])
self.TradingDay=self._to_bytes(i_tuple[31])
self.SettlementID=int(i_tuple[32])
self.OrderSysID=self._to_bytes(i_tuple[33])
self.OrderSource=self._to_bytes(i_tuple[34])
self.OrderStatus=self._to_bytes(i_tuple[35])
self.OrderType=self._to_bytes(i_tuple[36])
self.VolumeTraded=int(i_tuple[37])
self.VolumeTotal=int(i_tuple[38])
self.InsertDate=self._to_bytes(i_tuple[39])
self.InsertTime=self._to_bytes(i_tuple[40])
self.ActiveTime=self._to_bytes(i_tuple[41])
self.SuspendTime=self._to_bytes(i_tuple[42])
self.UpdateTime=self._to_bytes(i_tuple[43])
self.CancelTime=self._to_bytes(i_tuple[44])
self.ActiveTraderID=self._to_bytes(i_tuple[45])
self.ClearingPartID=self._to_bytes(i_tuple[46])
self.SequenceNo=int(i_tuple[47])
self.FrontID=int(i_tuple[48])
self.SessionID=int(i_tuple[49])
self.UserProductInfo=self._to_bytes(i_tuple[50])
self.StatusMsg=self._to_bytes(i_tuple[51])
self.UserForceClose=int(i_tuple[52])
self.ActiveUserID=self._to_bytes(i_tuple[53])
self.BrokerOrderSeq=int(i_tuple[54])
self.RelativeOrderSysID=self._to_bytes(i_tuple[55])
self.ZCETotalTradedVolume=int(i_tuple[56])
self.ErrorID=int(i_tuple[57])
self.ErrorMsg=self._to_bytes(i_tuple[58])
self.IsSwapOrder=int(i_tuple[59])
self.BranchID=self._to_bytes(i_tuple[60])
self.InvestUnitID=self._to_bytes(i_tuple[61])
self.AccountID=self._to_bytes(i_tuple[62])
self.CurrencyID=self._to_bytes(i_tuple[63])
self.IPAddress=self._to_bytes(i_tuple[64])
self.MacAddress=self._to_bytes(i_tuple[65])
class QryErrOrderActionField(Base):
"""查询错误报单操作"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
]
def __init__(self,BrokerID= '',InvestorID=''):
super(QryErrOrderActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
class ErrOrderActionField(Base):
"""错误报单操作"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('OrderActionRef',ctypes.c_int)# 报单操作引用
,('OrderRef',ctypes.c_char*13)# 报单引用
,('RequestID',ctypes.c_int)# 请求编号
,('FrontID',ctypes.c_int)# 前置编号
,('SessionID',ctypes.c_int)# 会话编号
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('OrderSysID',ctypes.c_char*21)# 报单编号
,('ActionFlag',ctypes.c_char)# 操作标志
,('LimitPrice',ctypes.c_double)# 价格
,('VolumeChange',ctypes.c_int)# 数量变化
,('ActionDate',ctypes.c_char*9)# 操作日期
,('ActionTime',ctypes.c_char*9)# 操作时间
,('TraderID',ctypes.c_char*21)# 交易所交易员代码
,('InstallID',ctypes.c_int)# 安装编号
,('OrderLocalID',ctypes.c_char*13)# 本地报单编号
,('ActionLocalID',ctypes.c_char*13)# 操作本地编号
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ClientID',ctypes.c_char*11)# 客户代码
,('BusinessUnit',ctypes.c_char*21)# 业务单元
,('OrderActionStatus',ctypes.c_char)# 报单操作状态
,('UserID',ctypes.c_char*16)# 用户代码
,('StatusMsg',ctypes.c_char*81)# 状态信息
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('BranchID',ctypes.c_char*9)# 营业部编号
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
,('IPAddress',ctypes.c_char*16)# IP地址
,('MacAddress',ctypes.c_char*21)# Mac地址
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
]
def __init__(self,BrokerID= '',InvestorID='',OrderActionRef=0,OrderRef='',RequestID=0,FrontID=0,SessionID=0,ExchangeID='',OrderSysID='',ActionFlag='',LimitPrice=0.0,VolumeChange=0,ActionDate='',ActionTime='',TraderID='',InstallID=0,OrderLocalID='',ActionLocalID='',ParticipantID='',ClientID='',BusinessUnit='',OrderActionStatus='',UserID='',StatusMsg='',InstrumentID='',BranchID='',InvestUnitID='',IPAddress='',MacAddress='',ErrorID=0,ErrorMsg=''):
super(ErrOrderActionField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.OrderActionRef=int(OrderActionRef)
self.OrderRef=self._to_bytes(OrderRef)
self.RequestID=int(RequestID)
self.FrontID=int(FrontID)
self.SessionID=int(SessionID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.OrderSysID=self._to_bytes(OrderSysID)
self.ActionFlag=self._to_bytes(ActionFlag)
self.LimitPrice=float(LimitPrice)
self.VolumeChange=int(VolumeChange)
self.ActionDate=self._to_bytes(ActionDate)
self.ActionTime=self._to_bytes(ActionTime)
self.TraderID=self._to_bytes(TraderID)
self.InstallID=int(InstallID)
self.OrderLocalID=self._to_bytes(OrderLocalID)
self.ActionLocalID=self._to_bytes(ActionLocalID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ClientID=self._to_bytes(ClientID)
self.BusinessUnit=self._to_bytes(BusinessUnit)
self.OrderActionStatus=self._to_bytes(OrderActionStatus)
self.UserID=self._to_bytes(UserID)
self.StatusMsg=self._to_bytes(StatusMsg)
self.InstrumentID=self._to_bytes(InstrumentID)
self.BranchID=self._to_bytes(BranchID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
self.IPAddress=self._to_bytes(IPAddress)
self.MacAddress=self._to_bytes(MacAddress)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.OrderActionRef=int(i_tuple[3])
self.OrderRef=self._to_bytes(i_tuple[4])
self.RequestID=int(i_tuple[5])
self.FrontID=int(i_tuple[6])
self.SessionID=int(i_tuple[7])
self.ExchangeID=self._to_bytes(i_tuple[8])
self.OrderSysID=self._to_bytes(i_tuple[9])
self.ActionFlag=self._to_bytes(i_tuple[10])
self.LimitPrice=float(i_tuple[11])
self.VolumeChange=int(i_tuple[12])
self.ActionDate=self._to_bytes(i_tuple[13])
self.ActionTime=self._to_bytes(i_tuple[14])
self.TraderID=self._to_bytes(i_tuple[15])
self.InstallID=int(i_tuple[16])
self.OrderLocalID=self._to_bytes(i_tuple[17])
self.ActionLocalID=self._to_bytes(i_tuple[18])
self.ParticipantID=self._to_bytes(i_tuple[19])
self.ClientID=self._to_bytes(i_tuple[20])
self.BusinessUnit=self._to_bytes(i_tuple[21])
self.OrderActionStatus=self._to_bytes(i_tuple[22])
self.UserID=self._to_bytes(i_tuple[23])
self.StatusMsg=self._to_bytes(i_tuple[24])
self.InstrumentID=self._to_bytes(i_tuple[25])
self.BranchID=self._to_bytes(i_tuple[26])
self.InvestUnitID=self._to_bytes(i_tuple[27])
self.IPAddress=self._to_bytes(i_tuple[28])
self.MacAddress=self._to_bytes(i_tuple[29])
self.ErrorID=int(i_tuple[30])
self.ErrorMsg=self._to_bytes(i_tuple[31])
class QryExchangeSequenceField(Base):
"""查询交易所状态"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
]
def __init__(self,ExchangeID= ''):
super(QryExchangeSequenceField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
class ExchangeSequenceField(Base):
"""交易所状态"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('SequenceNo',ctypes.c_int)# 序号
,('MarketStatus',ctypes.c_char)# 合约交易状态
]
def __init__(self,ExchangeID= '',SequenceNo=0,MarketStatus=''):
super(ExchangeSequenceField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.SequenceNo=int(SequenceNo)
self.MarketStatus=self._to_bytes(MarketStatus)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.SequenceNo=int(i_tuple[2])
self.MarketStatus=self._to_bytes(i_tuple[3])
class QueryMaxOrderVolumeWithPriceField(Base):
"""根据价格查询最大报单数量"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('Direction',ctypes.c_char)# 买卖方向
,('OffsetFlag',ctypes.c_char)# 开平标志
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('MaxVolume',ctypes.c_int)# 最大允许报单数量
,('Price',ctypes.c_double)# 报单价格
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InstrumentID='',Direction='',OffsetFlag='',HedgeFlag='',MaxVolume=0,Price=0.0,ExchangeID='',InvestUnitID=''):
super(QueryMaxOrderVolumeWithPriceField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.Direction=self._to_bytes(Direction)
self.OffsetFlag=self._to_bytes(OffsetFlag)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.MaxVolume=int(MaxVolume)
self.Price=float(Price)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.Direction=self._to_bytes(i_tuple[4])
self.OffsetFlag=self._to_bytes(i_tuple[5])
self.HedgeFlag=self._to_bytes(i_tuple[6])
self.MaxVolume=int(i_tuple[7])
self.Price=float(i_tuple[8])
self.ExchangeID=self._to_bytes(i_tuple[9])
self.InvestUnitID=self._to_bytes(i_tuple[10])
class QryBrokerTradingParamsField(Base):
"""查询经纪公司交易参数"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('AccountID',ctypes.c_char*13)# 投资者帐号
]
def __init__(self,BrokerID= '',InvestorID='',CurrencyID='',AccountID=''):
super(QryBrokerTradingParamsField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.CurrencyID=self._to_bytes(CurrencyID)
self.AccountID=self._to_bytes(AccountID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.CurrencyID=self._to_bytes(i_tuple[3])
self.AccountID=self._to_bytes(i_tuple[4])
class BrokerTradingParamsField(Base):
"""经纪公司交易参数"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('MarginPriceType',ctypes.c_char)# 保证金价格类型
,('Algorithm',ctypes.c_char)# 盈亏算法
,('AvailIncludeCloseProfit',ctypes.c_char)# 可用是否包含平仓盈利
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('OptionRoyaltyPriceType',ctypes.c_char)# 期权权利金价格类型
,('AccountID',ctypes.c_char*13)# 投资者帐号
]
def __init__(self,BrokerID= '',InvestorID='',MarginPriceType='',Algorithm='',AvailIncludeCloseProfit='',CurrencyID='',OptionRoyaltyPriceType='',AccountID=''):
super(BrokerTradingParamsField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.MarginPriceType=self._to_bytes(MarginPriceType)
self.Algorithm=self._to_bytes(Algorithm)
self.AvailIncludeCloseProfit=self._to_bytes(AvailIncludeCloseProfit)
self.CurrencyID=self._to_bytes(CurrencyID)
self.OptionRoyaltyPriceType=self._to_bytes(OptionRoyaltyPriceType)
self.AccountID=self._to_bytes(AccountID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.MarginPriceType=self._to_bytes(i_tuple[3])
self.Algorithm=self._to_bytes(i_tuple[4])
self.AvailIncludeCloseProfit=self._to_bytes(i_tuple[5])
self.CurrencyID=self._to_bytes(i_tuple[6])
self.OptionRoyaltyPriceType=self._to_bytes(i_tuple[7])
self.AccountID=self._to_bytes(i_tuple[8])
class QryBrokerTradingAlgosField(Base):
"""查询经纪公司交易算法"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
]
def __init__(self,BrokerID= '',ExchangeID='',InstrumentID=''):
super(QryBrokerTradingAlgosField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InstrumentID=self._to_bytes(InstrumentID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.ExchangeID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
class BrokerTradingAlgosField(Base):
"""经纪公司交易算法"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('HandlePositionAlgoID',ctypes.c_char)# 持仓处理算法编号
,('FindMarginRateAlgoID',ctypes.c_char)# 寻找保证金率算法编号
,('HandleTradingAccountAlgoID',ctypes.c_char)# 资金处理算法编号
]
def __init__(self,BrokerID= '',ExchangeID='',InstrumentID='',HandlePositionAlgoID='',FindMarginRateAlgoID='',HandleTradingAccountAlgoID=''):
super(BrokerTradingAlgosField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.HandlePositionAlgoID=self._to_bytes(HandlePositionAlgoID)
self.FindMarginRateAlgoID=self._to_bytes(FindMarginRateAlgoID)
self.HandleTradingAccountAlgoID=self._to_bytes(HandleTradingAccountAlgoID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.ExchangeID=self._to_bytes(i_tuple[2])
self.InstrumentID=self._to_bytes(i_tuple[3])
self.HandlePositionAlgoID=self._to_bytes(i_tuple[4])
self.FindMarginRateAlgoID=self._to_bytes(i_tuple[5])
self.HandleTradingAccountAlgoID=self._to_bytes(i_tuple[6])
class QueryBrokerDepositField(Base):
"""查询经纪公司资金"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
]
def __init__(self,BrokerID= '',ExchangeID=''):
super(QueryBrokerDepositField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.ExchangeID=self._to_bytes(i_tuple[2])
class BrokerDepositField(Base):
"""经纪公司资金"""
_fields_ = [
('TradingDay',ctypes.c_char*9)# ///交易日期
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('ParticipantID',ctypes.c_char*11)# 会员代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('PreBalance',ctypes.c_double)# 上次结算准备金
,('CurrMargin',ctypes.c_double)# 当前保证金总额
,('CloseProfit',ctypes.c_double)# 平仓盈亏
,('Balance',ctypes.c_double)# 期货结算准备金
,('Deposit',ctypes.c_double)# 入金金额
,('Withdraw',ctypes.c_double)# 出金金额
,('Available',ctypes.c_double)# 可提资金
,('Reserve',ctypes.c_double)# 基本准备金
,('FrozenMargin',ctypes.c_double)# 冻结的保证金
]
def __init__(self,TradingDay= '',BrokerID='',ParticipantID='',ExchangeID='',PreBalance=0.0,CurrMargin=0.0,CloseProfit=0.0,Balance=0.0,Deposit=0.0,Withdraw=0.0,Available=0.0,Reserve=0.0,FrozenMargin=0.0):
super(BrokerDepositField,self).__init__()
self.TradingDay=self._to_bytes(TradingDay)
self.BrokerID=self._to_bytes(BrokerID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.PreBalance=float(PreBalance)
self.CurrMargin=float(CurrMargin)
self.CloseProfit=float(CloseProfit)
self.Balance=float(Balance)
self.Deposit=float(Deposit)
self.Withdraw=float(Withdraw)
self.Available=float(Available)
self.Reserve=float(Reserve)
self.FrozenMargin=float(FrozenMargin)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradingDay=self._to_bytes(i_tuple[1])
self.BrokerID=self._to_bytes(i_tuple[2])
self.ParticipantID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.PreBalance=float(i_tuple[5])
self.CurrMargin=float(i_tuple[6])
self.CloseProfit=float(i_tuple[7])
self.Balance=float(i_tuple[8])
self.Deposit=float(i_tuple[9])
self.Withdraw=float(i_tuple[10])
self.Available=float(i_tuple[11])
self.Reserve=float(i_tuple[12])
self.FrozenMargin=float(i_tuple[13])
class QryCFMMCBrokerKeyField(Base):
"""查询保证金监管系统经纪公司密钥"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
]
def __init__(self,BrokerID= ''):
super(QryCFMMCBrokerKeyField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
class CFMMCBrokerKeyField(Base):
"""保证金监管系统经纪公司密钥"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('ParticipantID',ctypes.c_char*11)# 经纪公司统一编码
,('CreateDate',ctypes.c_char*9)# 密钥生成日期
,('CreateTime',ctypes.c_char*9)# 密钥生成时间
,('KeyID',ctypes.c_int)# 密钥编号
,('CurrentKey',ctypes.c_char*21)# 动态密钥
,('KeyKind',ctypes.c_char)# 动态密钥类型
]
def __init__(self,BrokerID= '',ParticipantID='',CreateDate='',CreateTime='',KeyID=0,CurrentKey='',KeyKind=''):
super(CFMMCBrokerKeyField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.CreateDate=self._to_bytes(CreateDate)
self.CreateTime=self._to_bytes(CreateTime)
self.KeyID=int(KeyID)
self.CurrentKey=self._to_bytes(CurrentKey)
self.KeyKind=self._to_bytes(KeyKind)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.ParticipantID=self._to_bytes(i_tuple[2])
self.CreateDate=self._to_bytes(i_tuple[3])
self.CreateTime=self._to_bytes(i_tuple[4])
self.KeyID=int(i_tuple[5])
self.CurrentKey=self._to_bytes(i_tuple[6])
self.KeyKind=self._to_bytes(i_tuple[7])
class CFMMCTradingAccountKeyField(Base):
"""保证金监管系统经纪公司资金账户密钥"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('ParticipantID',ctypes.c_char*11)# 经纪公司统一编码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('KeyID',ctypes.c_int)# 密钥编号
,('CurrentKey',ctypes.c_char*21)# 动态密钥
]
def __init__(self,BrokerID= '',ParticipantID='',AccountID='',KeyID=0,CurrentKey=''):
super(CFMMCTradingAccountKeyField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.AccountID=self._to_bytes(AccountID)
self.KeyID=int(KeyID)
self.CurrentKey=self._to_bytes(CurrentKey)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.ParticipantID=self._to_bytes(i_tuple[2])
self.AccountID=self._to_bytes(i_tuple[3])
self.KeyID=int(i_tuple[4])
self.CurrentKey=self._to_bytes(i_tuple[5])
class QryCFMMCTradingAccountKeyField(Base):
"""请求查询保证金监管系统经纪公司资金账户密钥"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
]
def __init__(self,BrokerID= '',InvestorID=''):
super(QryCFMMCTradingAccountKeyField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
class BrokerUserOTPParamField(Base):
"""用户动态令牌参数"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('OTPVendorsID',ctypes.c_char*2)# 动态令牌提供商
,('SerialNumber',ctypes.c_char*17)# 动态令牌序列号
,('AuthKey',ctypes.c_char*41)# 令牌密钥
,('LastDrift',ctypes.c_int)# 漂移值
,('LastSuccess',ctypes.c_int)# 成功值
,('OTPType',ctypes.c_char)# 动态令牌类型
]
def __init__(self,BrokerID= '',UserID='',OTPVendorsID='',SerialNumber='',AuthKey='',LastDrift=0,LastSuccess=0,OTPType=''):
super(BrokerUserOTPParamField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.OTPVendorsID=self._to_bytes(OTPVendorsID)
self.SerialNumber=self._to_bytes(SerialNumber)
self.AuthKey=self._to_bytes(AuthKey)
self.LastDrift=int(LastDrift)
self.LastSuccess=int(LastSuccess)
self.OTPType=self._to_bytes(OTPType)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
self.OTPVendorsID=self._to_bytes(i_tuple[3])
self.SerialNumber=self._to_bytes(i_tuple[4])
self.AuthKey=self._to_bytes(i_tuple[5])
self.LastDrift=int(i_tuple[6])
self.LastSuccess=int(i_tuple[7])
self.OTPType=self._to_bytes(i_tuple[8])
class ManualSyncBrokerUserOTPField(Base):
"""手工同步用户动态令牌"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('OTPType',ctypes.c_char)# 动态令牌类型
,('FirstOTP',ctypes.c_char*41)# 第一个动态密码
,('SecondOTP',ctypes.c_char*41)# 第二个动态密码
]
def __init__(self,BrokerID= '',UserID='',OTPType='',FirstOTP='',SecondOTP=''):
super(ManualSyncBrokerUserOTPField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.OTPType=self._to_bytes(OTPType)
self.FirstOTP=self._to_bytes(FirstOTP)
self.SecondOTP=self._to_bytes(SecondOTP)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
self.OTPType=self._to_bytes(i_tuple[3])
self.FirstOTP=self._to_bytes(i_tuple[4])
self.SecondOTP=self._to_bytes(i_tuple[5])
class CommRateModelField(Base):
"""投资者手续费率模板"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('CommModelID',ctypes.c_char*13)# 手续费率模板代码
,('CommModelName',ctypes.c_char*161)# 模板名称
]
def __init__(self,BrokerID= '',CommModelID='',CommModelName=''):
super(CommRateModelField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.CommModelID=self._to_bytes(CommModelID)
self.CommModelName=self._to_bytes(CommModelName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.CommModelID=self._to_bytes(i_tuple[2])
self.CommModelName=self._to_bytes(i_tuple[3])
class QryCommRateModelField(Base):
"""请求查询投资者手续费率模板"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('CommModelID',ctypes.c_char*13)# 手续费率模板代码
]
def __init__(self,BrokerID= '',CommModelID=''):
super(QryCommRateModelField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.CommModelID=self._to_bytes(CommModelID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.CommModelID=self._to_bytes(i_tuple[2])
class MarginModelField(Base):
"""投资者保证金率模板"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('MarginModelID',ctypes.c_char*13)# 保证金率模板代码
,('MarginModelName',ctypes.c_char*161)# 模板名称
]
def __init__(self,BrokerID= '',MarginModelID='',MarginModelName=''):
super(MarginModelField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.MarginModelID=self._to_bytes(MarginModelID)
self.MarginModelName=self._to_bytes(MarginModelName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.MarginModelID=self._to_bytes(i_tuple[2])
self.MarginModelName=self._to_bytes(i_tuple[3])
class QryMarginModelField(Base):
"""请求查询投资者保证金率模板"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('MarginModelID',ctypes.c_char*13)# 保证金率模板代码
]
def __init__(self,BrokerID= '',MarginModelID=''):
super(QryMarginModelField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.MarginModelID=self._to_bytes(MarginModelID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.MarginModelID=self._to_bytes(i_tuple[2])
class EWarrantOffsetField(Base):
"""仓单折抵信息"""
_fields_ = [
('TradingDay',ctypes.c_char*9)# ///交易日期
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('Direction',ctypes.c_char)# 买卖方向
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('Volume',ctypes.c_int)# 数量
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,TradingDay= '',BrokerID='',InvestorID='',ExchangeID='',InstrumentID='',Direction='',HedgeFlag='',Volume=0,InvestUnitID=''):
super(EWarrantOffsetField,self).__init__()
self.TradingDay=self._to_bytes(TradingDay)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.Direction=self._to_bytes(Direction)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.Volume=int(Volume)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradingDay=self._to_bytes(i_tuple[1])
self.BrokerID=self._to_bytes(i_tuple[2])
self.InvestorID=self._to_bytes(i_tuple[3])
self.ExchangeID=self._to_bytes(i_tuple[4])
self.InstrumentID=self._to_bytes(i_tuple[5])
self.Direction=self._to_bytes(i_tuple[6])
self.HedgeFlag=self._to_bytes(i_tuple[7])
self.Volume=int(i_tuple[8])
self.InvestUnitID=self._to_bytes(i_tuple[9])
class QryEWarrantOffsetField(Base):
"""查询仓单折抵信息"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InstrumentID',ctypes.c_char*31)# 合约代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',ExchangeID='',InstrumentID='',InvestUnitID=''):
super(QryEWarrantOffsetField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InstrumentID=self._to_bytes(InstrumentID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.ExchangeID=self._to_bytes(i_tuple[3])
self.InstrumentID=self._to_bytes(i_tuple[4])
self.InvestUnitID=self._to_bytes(i_tuple[5])
class QryInvestorProductGroupMarginField(Base):
"""查询投资者品种/跨品种保证金"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('ProductGroupID',ctypes.c_char*31)# 品种/跨品种标示
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',ProductGroupID='',HedgeFlag='',ExchangeID='',InvestUnitID=''):
super(QryInvestorProductGroupMarginField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.ProductGroupID=self._to_bytes(ProductGroupID)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.ProductGroupID=self._to_bytes(i_tuple[3])
self.HedgeFlag=self._to_bytes(i_tuple[4])
self.ExchangeID=self._to_bytes(i_tuple[5])
self.InvestUnitID=self._to_bytes(i_tuple[6])
class InvestorProductGroupMarginField(Base):
"""投资者品种/跨品种保证金"""
_fields_ = [
('ProductGroupID',ctypes.c_char*31)# ///品种/跨品种标示
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('TradingDay',ctypes.c_char*9)# 交易日
,('SettlementID',ctypes.c_int)# 结算编号
,('FrozenMargin',ctypes.c_double)# 冻结的保证金
,('LongFrozenMargin',ctypes.c_double)# 多头冻结的保证金
,('ShortFrozenMargin',ctypes.c_double)# 空头冻结的保证金
,('UseMargin',ctypes.c_double)# 占用的保证金
,('LongUseMargin',ctypes.c_double)# 多头保证金
,('ShortUseMargin',ctypes.c_double)# 空头保证金
,('ExchMargin',ctypes.c_double)# 交易所保证金
,('LongExchMargin',ctypes.c_double)# 交易所多头保证金
,('ShortExchMargin',ctypes.c_double)# 交易所空头保证金
,('CloseProfit',ctypes.c_double)# 平仓盈亏
,('FrozenCommission',ctypes.c_double)# 冻结的手续费
,('Commission',ctypes.c_double)# 手续费
,('FrozenCash',ctypes.c_double)# 冻结的资金
,('CashIn',ctypes.c_double)# 资金差额
,('PositionProfit',ctypes.c_double)# 持仓盈亏
,('OffsetAmount',ctypes.c_double)# 折抵总金额
,('LongOffsetAmount',ctypes.c_double)# 多头折抵总金额
,('ShortOffsetAmount',ctypes.c_double)# 空头折抵总金额
,('ExchOffsetAmount',ctypes.c_double)# 交易所折抵总金额
,('LongExchOffsetAmount',ctypes.c_double)# 交易所多头折抵总金额
,('ShortExchOffsetAmount',ctypes.c_double)# 交易所空头折抵总金额
,('HedgeFlag',ctypes.c_char)# 投机套保标志
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,ProductGroupID= '',BrokerID='',InvestorID='',TradingDay='',SettlementID=0,FrozenMargin=0.0,LongFrozenMargin=0.0,ShortFrozenMargin=0.0,UseMargin=0.0,LongUseMargin=0.0,ShortUseMargin=0.0,ExchMargin=0.0,LongExchMargin=0.0,ShortExchMargin=0.0,CloseProfit=0.0,FrozenCommission=0.0,Commission=0.0,FrozenCash=0.0,CashIn=0.0,PositionProfit=0.0,OffsetAmount=0.0,LongOffsetAmount=0.0,ShortOffsetAmount=0.0,ExchOffsetAmount=0.0,LongExchOffsetAmount=0.0,ShortExchOffsetAmount=0.0,HedgeFlag='',ExchangeID='',InvestUnitID=''):
super(InvestorProductGroupMarginField,self).__init__()
self.ProductGroupID=self._to_bytes(ProductGroupID)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.TradingDay=self._to_bytes(TradingDay)
self.SettlementID=int(SettlementID)
self.FrozenMargin=float(FrozenMargin)
self.LongFrozenMargin=float(LongFrozenMargin)
self.ShortFrozenMargin=float(ShortFrozenMargin)
self.UseMargin=float(UseMargin)
self.LongUseMargin=float(LongUseMargin)
self.ShortUseMargin=float(ShortUseMargin)
self.ExchMargin=float(ExchMargin)
self.LongExchMargin=float(LongExchMargin)
self.ShortExchMargin=float(ShortExchMargin)
self.CloseProfit=float(CloseProfit)
self.FrozenCommission=float(FrozenCommission)
self.Commission=float(Commission)
self.FrozenCash=float(FrozenCash)
self.CashIn=float(CashIn)
self.PositionProfit=float(PositionProfit)
self.OffsetAmount=float(OffsetAmount)
self.LongOffsetAmount=float(LongOffsetAmount)
self.ShortOffsetAmount=float(ShortOffsetAmount)
self.ExchOffsetAmount=float(ExchOffsetAmount)
self.LongExchOffsetAmount=float(LongExchOffsetAmount)
self.ShortExchOffsetAmount=float(ShortExchOffsetAmount)
self.HedgeFlag=self._to_bytes(HedgeFlag)
self.ExchangeID=self._to_bytes(ExchangeID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ProductGroupID=self._to_bytes(i_tuple[1])
self.BrokerID=self._to_bytes(i_tuple[2])
self.InvestorID=self._to_bytes(i_tuple[3])
self.TradingDay=self._to_bytes(i_tuple[4])
self.SettlementID=int(i_tuple[5])
self.FrozenMargin=float(i_tuple[6])
self.LongFrozenMargin=float(i_tuple[7])
self.ShortFrozenMargin=float(i_tuple[8])
self.UseMargin=float(i_tuple[9])
self.LongUseMargin=float(i_tuple[10])
self.ShortUseMargin=float(i_tuple[11])
self.ExchMargin=float(i_tuple[12])
self.LongExchMargin=float(i_tuple[13])
self.ShortExchMargin=float(i_tuple[14])
self.CloseProfit=float(i_tuple[15])
self.FrozenCommission=float(i_tuple[16])
self.Commission=float(i_tuple[17])
self.FrozenCash=float(i_tuple[18])
self.CashIn=float(i_tuple[19])
self.PositionProfit=float(i_tuple[20])
self.OffsetAmount=float(i_tuple[21])
self.LongOffsetAmount=float(i_tuple[22])
self.ShortOffsetAmount=float(i_tuple[23])
self.ExchOffsetAmount=float(i_tuple[24])
self.LongExchOffsetAmount=float(i_tuple[25])
self.ShortExchOffsetAmount=float(i_tuple[26])
self.HedgeFlag=self._to_bytes(i_tuple[27])
self.ExchangeID=self._to_bytes(i_tuple[28])
self.InvestUnitID=self._to_bytes(i_tuple[29])
class QueryCFMMCTradingAccountTokenField(Base):
"""查询监控中心用户令牌"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('InvestUnitID',ctypes.c_char*17)# 投资单元代码
]
def __init__(self,BrokerID= '',InvestorID='',InvestUnitID=''):
super(QueryCFMMCTradingAccountTokenField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.InvestUnitID=self._to_bytes(InvestUnitID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2])
self.InvestUnitID=self._to_bytes(i_tuple[3])
class CFMMCTradingAccountTokenField(Base):
"""监控中心用户令牌"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('ParticipantID',ctypes.c_char*11)# 经纪公司统一编码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('KeyID',ctypes.c_int)# 密钥编号
,('Token',ctypes.c_char*21)# 动态令牌
]
def __init__(self,BrokerID= '',ParticipantID='',AccountID='',KeyID=0,Token=''):
super(CFMMCTradingAccountTokenField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.ParticipantID=self._to_bytes(ParticipantID)
self.AccountID=self._to_bytes(AccountID)
self.KeyID=int(KeyID)
self.Token=self._to_bytes(Token)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.ParticipantID=self._to_bytes(i_tuple[2])
self.AccountID=self._to_bytes(i_tuple[3])
self.KeyID=int(i_tuple[4])
self.Token=self._to_bytes(i_tuple[5])
class QryProductGroupField(Base):
"""查询产品组"""
_fields_ = [
('ProductID',ctypes.c_char*31)# ///产品代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
]
def __init__(self,ProductID= '',ExchangeID=''):
super(QryProductGroupField,self).__init__()
self.ProductID=self._to_bytes(ProductID)
self.ExchangeID=self._to_bytes(ExchangeID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ProductID=self._to_bytes(i_tuple[1])
self.ExchangeID=self._to_bytes(i_tuple[2])
class ProductGroupField(Base):
"""投资者品种/跨品种保证金产品组"""
_fields_ = [
('ProductID',ctypes.c_char*31)# ///产品代码
,('ExchangeID',ctypes.c_char*9)# 交易所代码
,('ProductGroupID',ctypes.c_char*31)# 产品组代码
]
def __init__(self,ProductID= '',ExchangeID='',ProductGroupID=''):
super(ProductGroupField,self).__init__()
self.ProductID=self._to_bytes(ProductID)
self.ExchangeID=self._to_bytes(ExchangeID)
self.ProductGroupID=self._to_bytes(ProductGroupID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ProductID=self._to_bytes(i_tuple[1])
self.ExchangeID=self._to_bytes(i_tuple[2])
self.ProductGroupID=self._to_bytes(i_tuple[3])
class BulletinField(Base):
"""交易所公告"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('TradingDay',ctypes.c_char*9)# 交易日
,('BulletinID',ctypes.c_int)# 公告编号
,('SequenceNo',ctypes.c_int)# 序列号
,('NewsType',ctypes.c_char*3)# 公告类型
,('NewsUrgency',ctypes.c_char)# 紧急程度
,('SendTime',ctypes.c_char*9)# 发送时间
,('Abstract',ctypes.c_char*81)# 消息摘要
,('ComeFrom',ctypes.c_char*21)# 消息来源
,('Content',ctypes.c_char*501)# 消息正文
,('URLLink',ctypes.c_char*201)# WEB地址
,('MarketID',ctypes.c_char*31)# 市场代码
]
def __init__(self,ExchangeID= '',TradingDay='',BulletinID=0,SequenceNo=0,NewsType='',NewsUrgency='',SendTime='',Abstract='',ComeFrom='',Content='',URLLink='',MarketID=''):
super(BulletinField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.TradingDay=self._to_bytes(TradingDay)
self.BulletinID=int(BulletinID)
self.SequenceNo=int(SequenceNo)
self.NewsType=self._to_bytes(NewsType)
self.NewsUrgency=self._to_bytes(NewsUrgency)
self.SendTime=self._to_bytes(SendTime)
self.Abstract=self._to_bytes(Abstract)
self.ComeFrom=self._to_bytes(ComeFrom)
self.Content=self._to_bytes(Content)
self.URLLink=self._to_bytes(URLLink)
self.MarketID=self._to_bytes(MarketID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.TradingDay=self._to_bytes(i_tuple[2])
self.BulletinID=int(i_tuple[3])
self.SequenceNo=int(i_tuple[4])
self.NewsType=self._to_bytes(i_tuple[5])
self.NewsUrgency=self._to_bytes(i_tuple[6])
self.SendTime=self._to_bytes(i_tuple[7])
self.Abstract=self._to_bytes(i_tuple[8])
self.ComeFrom=self._to_bytes(i_tuple[9])
self.Content=self._to_bytes(i_tuple[10])
self.URLLink=self._to_bytes(i_tuple[11])
self.MarketID=self._to_bytes(i_tuple[12])
class QryBulletinField(Base):
"""查询交易所公告"""
_fields_ = [
('ExchangeID',ctypes.c_char*9)# ///交易所代码
,('BulletinID',ctypes.c_int)# 公告编号
,('SequenceNo',ctypes.c_int)# 序列号
,('NewsType',ctypes.c_char*3)# 公告类型
,('NewsUrgency',ctypes.c_char)# 紧急程度
]
def __init__(self,ExchangeID= '',BulletinID=0,SequenceNo=0,NewsType='',NewsUrgency=''):
super(QryBulletinField,self).__init__()
self.ExchangeID=self._to_bytes(ExchangeID)
self.BulletinID=int(BulletinID)
self.SequenceNo=int(SequenceNo)
self.NewsType=self._to_bytes(NewsType)
self.NewsUrgency=self._to_bytes(NewsUrgency)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ExchangeID=self._to_bytes(i_tuple[1])
self.BulletinID=int(i_tuple[2])
self.SequenceNo=int(i_tuple[3])
self.NewsType=self._to_bytes(i_tuple[4])
self.NewsUrgency=self._to_bytes(i_tuple[5])
class ReqOpenAccountField(Base):
"""转帐开户请求"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('CustomerName',ctypes.c_char*51)# 客户姓名
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('Gender',ctypes.c_char)# 性别
,('CountryCode',ctypes.c_char*21)# 国家代码
,('CustType',ctypes.c_char)# 客户类型
,('Address',ctypes.c_char*101)# 地址
,('ZipCode',ctypes.c_char*7)# 邮编
,('Telephone',ctypes.c_char*41)# 电话号码
,('MobilePhone',ctypes.c_char*21)# 手机
,('Fax',ctypes.c_char*41)# 传真
,('EMail',ctypes.c_char*41)# 电子邮件
,('MoneyAccountStatus',ctypes.c_char)# 资金账户状态
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankPassWord',ctypes.c_char*41)# 银行密码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 期货密码
,('InstallID',ctypes.c_int)# 安装编号
,('VerifyCertNoFlag',ctypes.c_char)# 验证客户证件号码标志
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('CashExchangeCode',ctypes.c_char)# 汇钞标志
,('Digest',ctypes.c_char*36)# 摘要
,('BankAccType',ctypes.c_char)# 银行帐号类型
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BankSecuAccType',ctypes.c_char)# 期货单位帐号类型
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('BankSecuAcc',ctypes.c_char*41)# 期货单位帐号
,('BankPwdFlag',ctypes.c_char)# 银行密码标志
,('SecuPwdFlag',ctypes.c_char)# 期货资金密码核对标志
,('OperNo',ctypes.c_char*17)# 交易柜员
,('TID',ctypes.c_int)# 交易ID
,('UserID',ctypes.c_char*16)# 用户标识
,('LongCustomerName',ctypes.c_char*161)# 长客户姓名
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,CustomerName='',IdCardType='',IdentifiedCardNo='',Gender='',CountryCode='',CustType='',Address='',ZipCode='',Telephone='',MobilePhone='',Fax='',EMail='',MoneyAccountStatus='',BankAccount='',BankPassWord='',AccountID='',Password='',InstallID=0,VerifyCertNoFlag='',CurrencyID='',CashExchangeCode='',Digest='',BankAccType='',DeviceID='',BankSecuAccType='',BrokerIDByBank='',BankSecuAcc='',BankPwdFlag='',SecuPwdFlag='',OperNo='',TID=0,UserID='',LongCustomerName=''):
super(ReqOpenAccountField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.CustomerName=self._to_bytes(CustomerName)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.Gender=self._to_bytes(Gender)
self.CountryCode=self._to_bytes(CountryCode)
self.CustType=self._to_bytes(CustType)
self.Address=self._to_bytes(Address)
self.ZipCode=self._to_bytes(ZipCode)
self.Telephone=self._to_bytes(Telephone)
self.MobilePhone=self._to_bytes(MobilePhone)
self.Fax=self._to_bytes(Fax)
self.EMail=self._to_bytes(EMail)
self.MoneyAccountStatus=self._to_bytes(MoneyAccountStatus)
self.BankAccount=self._to_bytes(BankAccount)
self.BankPassWord=self._to_bytes(BankPassWord)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.InstallID=int(InstallID)
self.VerifyCertNoFlag=self._to_bytes(VerifyCertNoFlag)
self.CurrencyID=self._to_bytes(CurrencyID)
self.CashExchangeCode=self._to_bytes(CashExchangeCode)
self.Digest=self._to_bytes(Digest)
self.BankAccType=self._to_bytes(BankAccType)
self.DeviceID=self._to_bytes(DeviceID)
self.BankSecuAccType=self._to_bytes(BankSecuAccType)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.BankSecuAcc=self._to_bytes(BankSecuAcc)
self.BankPwdFlag=self._to_bytes(BankPwdFlag)
self.SecuPwdFlag=self._to_bytes(SecuPwdFlag)
self.OperNo=self._to_bytes(OperNo)
self.TID=int(TID)
self.UserID=self._to_bytes(UserID)
self.LongCustomerName=self._to_bytes(LongCustomerName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.CustomerName=self._to_bytes(i_tuple[13])
self.IdCardType=self._to_bytes(i_tuple[14])
self.IdentifiedCardNo=self._to_bytes(i_tuple[15])
self.Gender=self._to_bytes(i_tuple[16])
self.CountryCode=self._to_bytes(i_tuple[17])
self.CustType=self._to_bytes(i_tuple[18])
self.Address=self._to_bytes(i_tuple[19])
self.ZipCode=self._to_bytes(i_tuple[20])
self.Telephone=self._to_bytes(i_tuple[21])
self.MobilePhone=self._to_bytes(i_tuple[22])
self.Fax=self._to_bytes(i_tuple[23])
self.EMail=self._to_bytes(i_tuple[24])
self.MoneyAccountStatus=self._to_bytes(i_tuple[25])
self.BankAccount=self._to_bytes(i_tuple[26])
self.BankPassWord=self._to_bytes(i_tuple[27])
self.AccountID=self._to_bytes(i_tuple[28])
self.Password=self._to_bytes(i_tuple[29])
self.InstallID=int(i_tuple[30])
self.VerifyCertNoFlag=self._to_bytes(i_tuple[31])
self.CurrencyID=self._to_bytes(i_tuple[32])
self.CashExchangeCode=self._to_bytes(i_tuple[33])
self.Digest=self._to_bytes(i_tuple[34])
self.BankAccType=self._to_bytes(i_tuple[35])
self.DeviceID=self._to_bytes(i_tuple[36])
self.BankSecuAccType=self._to_bytes(i_tuple[37])
self.BrokerIDByBank=self._to_bytes(i_tuple[38])
self.BankSecuAcc=self._to_bytes(i_tuple[39])
self.BankPwdFlag=self._to_bytes(i_tuple[40])
self.SecuPwdFlag=self._to_bytes(i_tuple[41])
self.OperNo=self._to_bytes(i_tuple[42])
self.TID=int(i_tuple[43])
self.UserID=self._to_bytes(i_tuple[44])
self.LongCustomerName=self._to_bytes(i_tuple[45])
class ReqCancelAccountField(Base):
"""转帐销户请求"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('CustomerName',ctypes.c_char*51)# 客户姓名
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('Gender',ctypes.c_char)# 性别
,('CountryCode',ctypes.c_char*21)# 国家代码
,('CustType',ctypes.c_char)# 客户类型
,('Address',ctypes.c_char*101)# 地址
,('ZipCode',ctypes.c_char*7)# 邮编
,('Telephone',ctypes.c_char*41)# 电话号码
,('MobilePhone',ctypes.c_char*21)# 手机
,('Fax',ctypes.c_char*41)# 传真
,('EMail',ctypes.c_char*41)# 电子邮件
,('MoneyAccountStatus',ctypes.c_char)# 资金账户状态
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankPassWord',ctypes.c_char*41)# 银行密码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 期货密码
,('InstallID',ctypes.c_int)# 安装编号
,('VerifyCertNoFlag',ctypes.c_char)# 验证客户证件号码标志
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('CashExchangeCode',ctypes.c_char)# 汇钞标志
,('Digest',ctypes.c_char*36)# 摘要
,('BankAccType',ctypes.c_char)# 银行帐号类型
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BankSecuAccType',ctypes.c_char)# 期货单位帐号类型
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('BankSecuAcc',ctypes.c_char*41)# 期货单位帐号
,('BankPwdFlag',ctypes.c_char)# 银行密码标志
,('SecuPwdFlag',ctypes.c_char)# 期货资金密码核对标志
,('OperNo',ctypes.c_char*17)# 交易柜员
,('TID',ctypes.c_int)# 交易ID
,('UserID',ctypes.c_char*16)# 用户标识
,('LongCustomerName',ctypes.c_char*161)# 长客户姓名
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,CustomerName='',IdCardType='',IdentifiedCardNo='',Gender='',CountryCode='',CustType='',Address='',ZipCode='',Telephone='',MobilePhone='',Fax='',EMail='',MoneyAccountStatus='',BankAccount='',BankPassWord='',AccountID='',Password='',InstallID=0,VerifyCertNoFlag='',CurrencyID='',CashExchangeCode='',Digest='',BankAccType='',DeviceID='',BankSecuAccType='',BrokerIDByBank='',BankSecuAcc='',BankPwdFlag='',SecuPwdFlag='',OperNo='',TID=0,UserID='',LongCustomerName=''):
super(ReqCancelAccountField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.CustomerName=self._to_bytes(CustomerName)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.Gender=self._to_bytes(Gender)
self.CountryCode=self._to_bytes(CountryCode)
self.CustType=self._to_bytes(CustType)
self.Address=self._to_bytes(Address)
self.ZipCode=self._to_bytes(ZipCode)
self.Telephone=self._to_bytes(Telephone)
self.MobilePhone=self._to_bytes(MobilePhone)
self.Fax=self._to_bytes(Fax)
self.EMail=self._to_bytes(EMail)
self.MoneyAccountStatus=self._to_bytes(MoneyAccountStatus)
self.BankAccount=self._to_bytes(BankAccount)
self.BankPassWord=self._to_bytes(BankPassWord)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.InstallID=int(InstallID)
self.VerifyCertNoFlag=self._to_bytes(VerifyCertNoFlag)
self.CurrencyID=self._to_bytes(CurrencyID)
self.CashExchangeCode=self._to_bytes(CashExchangeCode)
self.Digest=self._to_bytes(Digest)
self.BankAccType=self._to_bytes(BankAccType)
self.DeviceID=self._to_bytes(DeviceID)
self.BankSecuAccType=self._to_bytes(BankSecuAccType)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.BankSecuAcc=self._to_bytes(BankSecuAcc)
self.BankPwdFlag=self._to_bytes(BankPwdFlag)
self.SecuPwdFlag=self._to_bytes(SecuPwdFlag)
self.OperNo=self._to_bytes(OperNo)
self.TID=int(TID)
self.UserID=self._to_bytes(UserID)
self.LongCustomerName=self._to_bytes(LongCustomerName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.CustomerName=self._to_bytes(i_tuple[13])
self.IdCardType=self._to_bytes(i_tuple[14])
self.IdentifiedCardNo=self._to_bytes(i_tuple[15])
self.Gender=self._to_bytes(i_tuple[16])
self.CountryCode=self._to_bytes(i_tuple[17])
self.CustType=self._to_bytes(i_tuple[18])
self.Address=self._to_bytes(i_tuple[19])
self.ZipCode=self._to_bytes(i_tuple[20])
self.Telephone=self._to_bytes(i_tuple[21])
self.MobilePhone=self._to_bytes(i_tuple[22])
self.Fax=self._to_bytes(i_tuple[23])
self.EMail=self._to_bytes(i_tuple[24])
self.MoneyAccountStatus=self._to_bytes(i_tuple[25])
self.BankAccount=self._to_bytes(i_tuple[26])
self.BankPassWord=self._to_bytes(i_tuple[27])
self.AccountID=self._to_bytes(i_tuple[28])
self.Password=self._to_bytes(i_tuple[29])
self.InstallID=int(i_tuple[30])
self.VerifyCertNoFlag=self._to_bytes(i_tuple[31])
self.CurrencyID=self._to_bytes(i_tuple[32])
self.CashExchangeCode=self._to_bytes(i_tuple[33])
self.Digest=self._to_bytes(i_tuple[34])
self.BankAccType=self._to_bytes(i_tuple[35])
self.DeviceID=self._to_bytes(i_tuple[36])
self.BankSecuAccType=self._to_bytes(i_tuple[37])
self.BrokerIDByBank=self._to_bytes(i_tuple[38])
self.BankSecuAcc=self._to_bytes(i_tuple[39])
self.BankPwdFlag=self._to_bytes(i_tuple[40])
self.SecuPwdFlag=self._to_bytes(i_tuple[41])
self.OperNo=self._to_bytes(i_tuple[42])
self.TID=int(i_tuple[43])
self.UserID=self._to_bytes(i_tuple[44])
self.LongCustomerName=self._to_bytes(i_tuple[45])
class ReqChangeAccountField(Base):
"""变更银行账户请求"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('CustomerName',ctypes.c_char*51)# 客户姓名
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('Gender',ctypes.c_char)# 性别
,('CountryCode',ctypes.c_char*21)# 国家代码
,('CustType',ctypes.c_char)# 客户类型
,('Address',ctypes.c_char*101)# 地址
,('ZipCode',ctypes.c_char*7)# 邮编
,('Telephone',ctypes.c_char*41)# 电话号码
,('MobilePhone',ctypes.c_char*21)# 手机
,('Fax',ctypes.c_char*41)# 传真
,('EMail',ctypes.c_char*41)# 电子邮件
,('MoneyAccountStatus',ctypes.c_char)# 资金账户状态
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankPassWord',ctypes.c_char*41)# 银行密码
,('NewBankAccount',ctypes.c_char*41)# 新银行帐号
,('NewBankPassWord',ctypes.c_char*41)# 新银行密码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 期货密码
,('BankAccType',ctypes.c_char)# 银行帐号类型
,('InstallID',ctypes.c_int)# 安装编号
,('VerifyCertNoFlag',ctypes.c_char)# 验证客户证件号码标志
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('BankPwdFlag',ctypes.c_char)# 银行密码标志
,('SecuPwdFlag',ctypes.c_char)# 期货资金密码核对标志
,('TID',ctypes.c_int)# 交易ID
,('Digest',ctypes.c_char*36)# 摘要
,('LongCustomerName',ctypes.c_char*161)# 长客户姓名
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,CustomerName='',IdCardType='',IdentifiedCardNo='',Gender='',CountryCode='',CustType='',Address='',ZipCode='',Telephone='',MobilePhone='',Fax='',EMail='',MoneyAccountStatus='',BankAccount='',BankPassWord='',NewBankAccount='',NewBankPassWord='',AccountID='',Password='',BankAccType='',InstallID=0,VerifyCertNoFlag='',CurrencyID='',BrokerIDByBank='',BankPwdFlag='',SecuPwdFlag='',TID=0,Digest='',LongCustomerName=''):
super(ReqChangeAccountField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.CustomerName=self._to_bytes(CustomerName)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.Gender=self._to_bytes(Gender)
self.CountryCode=self._to_bytes(CountryCode)
self.CustType=self._to_bytes(CustType)
self.Address=self._to_bytes(Address)
self.ZipCode=self._to_bytes(ZipCode)
self.Telephone=self._to_bytes(Telephone)
self.MobilePhone=self._to_bytes(MobilePhone)
self.Fax=self._to_bytes(Fax)
self.EMail=self._to_bytes(EMail)
self.MoneyAccountStatus=self._to_bytes(MoneyAccountStatus)
self.BankAccount=self._to_bytes(BankAccount)
self.BankPassWord=self._to_bytes(BankPassWord)
self.NewBankAccount=self._to_bytes(NewBankAccount)
self.NewBankPassWord=self._to_bytes(NewBankPassWord)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.BankAccType=self._to_bytes(BankAccType)
self.InstallID=int(InstallID)
self.VerifyCertNoFlag=self._to_bytes(VerifyCertNoFlag)
self.CurrencyID=self._to_bytes(CurrencyID)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.BankPwdFlag=self._to_bytes(BankPwdFlag)
self.SecuPwdFlag=self._to_bytes(SecuPwdFlag)
self.TID=int(TID)
self.Digest=self._to_bytes(Digest)
self.LongCustomerName=self._to_bytes(LongCustomerName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.CustomerName=self._to_bytes(i_tuple[13])
self.IdCardType=self._to_bytes(i_tuple[14])
self.IdentifiedCardNo=self._to_bytes(i_tuple[15])
self.Gender=self._to_bytes(i_tuple[16])
self.CountryCode=self._to_bytes(i_tuple[17])
self.CustType=self._to_bytes(i_tuple[18])
self.Address=self._to_bytes(i_tuple[19])
self.ZipCode=self._to_bytes(i_tuple[20])
self.Telephone=self._to_bytes(i_tuple[21])
self.MobilePhone=self._to_bytes(i_tuple[22])
self.Fax=self._to_bytes(i_tuple[23])
self.EMail=self._to_bytes(i_tuple[24])
self.MoneyAccountStatus=self._to_bytes(i_tuple[25])
self.BankAccount=self._to_bytes(i_tuple[26])
self.BankPassWord=self._to_bytes(i_tuple[27])
self.NewBankAccount=self._to_bytes(i_tuple[28])
self.NewBankPassWord=self._to_bytes(i_tuple[29])
self.AccountID=self._to_bytes(i_tuple[30])
self.Password=self._to_bytes(i_tuple[31])
self.BankAccType=self._to_bytes(i_tuple[32])
self.InstallID=int(i_tuple[33])
self.VerifyCertNoFlag=self._to_bytes(i_tuple[34])
self.CurrencyID=self._to_bytes(i_tuple[35])
self.BrokerIDByBank=self._to_bytes(i_tuple[36])
self.BankPwdFlag=self._to_bytes(i_tuple[37])
self.SecuPwdFlag=self._to_bytes(i_tuple[38])
self.TID=int(i_tuple[39])
self.Digest=self._to_bytes(i_tuple[40])
self.LongCustomerName=self._to_bytes(i_tuple[41])
class ReqTransferField(Base):
"""转账请求"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('CustomerName',ctypes.c_char*51)# 客户姓名
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('CustType',ctypes.c_char)# 客户类型
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankPassWord',ctypes.c_char*41)# 银行密码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 期货密码
,('InstallID',ctypes.c_int)# 安装编号
,('FutureSerial',ctypes.c_int)# 期货公司流水号
,('UserID',ctypes.c_char*16)# 用户标识
,('VerifyCertNoFlag',ctypes.c_char)# 验证客户证件号码标志
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('TradeAmount',ctypes.c_double)# 转帐金额
,('FutureFetchAmount',ctypes.c_double)# 期货可取金额
,('FeePayFlag',ctypes.c_char)# 费用支付标志
,('CustFee',ctypes.c_double)# 应收客户费用
,('BrokerFee',ctypes.c_double)# 应收期货公司费用
,('Message',ctypes.c_char*129)# 发送方给接收方的消息
,('Digest',ctypes.c_char*36)# 摘要
,('BankAccType',ctypes.c_char)# 银行帐号类型
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BankSecuAccType',ctypes.c_char)# 期货单位帐号类型
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('BankSecuAcc',ctypes.c_char*41)# 期货单位帐号
,('BankPwdFlag',ctypes.c_char)# 银行密码标志
,('SecuPwdFlag',ctypes.c_char)# 期货资金密码核对标志
,('OperNo',ctypes.c_char*17)# 交易柜员
,('RequestID',ctypes.c_int)# 请求编号
,('TID',ctypes.c_int)# 交易ID
,('TransferStatus',ctypes.c_char)# 转账交易状态
,('LongCustomerName',ctypes.c_char*161)# 长客户姓名
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,CustomerName='',IdCardType='',IdentifiedCardNo='',CustType='',BankAccount='',BankPassWord='',AccountID='',Password='',InstallID=0,FutureSerial=0,UserID='',VerifyCertNoFlag='',CurrencyID='',TradeAmount=0.0,FutureFetchAmount=0.0,FeePayFlag='',CustFee=0.0,BrokerFee=0.0,Message='',Digest='',BankAccType='',DeviceID='',BankSecuAccType='',BrokerIDByBank='',BankSecuAcc='',BankPwdFlag='',SecuPwdFlag='',OperNo='',RequestID=0,TID=0,TransferStatus='',LongCustomerName=''):
super(ReqTransferField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.CustomerName=self._to_bytes(CustomerName)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.CustType=self._to_bytes(CustType)
self.BankAccount=self._to_bytes(BankAccount)
self.BankPassWord=self._to_bytes(BankPassWord)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.InstallID=int(InstallID)
self.FutureSerial=int(FutureSerial)
self.UserID=self._to_bytes(UserID)
self.VerifyCertNoFlag=self._to_bytes(VerifyCertNoFlag)
self.CurrencyID=self._to_bytes(CurrencyID)
self.TradeAmount=float(TradeAmount)
self.FutureFetchAmount=float(FutureFetchAmount)
self.FeePayFlag=self._to_bytes(FeePayFlag)
self.CustFee=float(CustFee)
self.BrokerFee=float(BrokerFee)
self.Message=self._to_bytes(Message)
self.Digest=self._to_bytes(Digest)
self.BankAccType=self._to_bytes(BankAccType)
self.DeviceID=self._to_bytes(DeviceID)
self.BankSecuAccType=self._to_bytes(BankSecuAccType)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.BankSecuAcc=self._to_bytes(BankSecuAcc)
self.BankPwdFlag=self._to_bytes(BankPwdFlag)
self.SecuPwdFlag=self._to_bytes(SecuPwdFlag)
self.OperNo=self._to_bytes(OperNo)
self.RequestID=int(RequestID)
self.TID=int(TID)
self.TransferStatus=self._to_bytes(TransferStatus)
self.LongCustomerName=self._to_bytes(LongCustomerName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.CustomerName=self._to_bytes(i_tuple[13])
self.IdCardType=self._to_bytes(i_tuple[14])
self.IdentifiedCardNo=self._to_bytes(i_tuple[15])
self.CustType=self._to_bytes(i_tuple[16])
self.BankAccount=self._to_bytes(i_tuple[17])
self.BankPassWord=self._to_bytes(i_tuple[18])
self.AccountID=self._to_bytes(i_tuple[19])
self.Password=self._to_bytes(i_tuple[20])
self.InstallID=int(i_tuple[21])
self.FutureSerial=int(i_tuple[22])
self.UserID=self._to_bytes(i_tuple[23])
self.VerifyCertNoFlag=self._to_bytes(i_tuple[24])
self.CurrencyID=self._to_bytes(i_tuple[25])
self.TradeAmount=float(i_tuple[26])
self.FutureFetchAmount=float(i_tuple[27])
self.FeePayFlag=self._to_bytes(i_tuple[28])
self.CustFee=float(i_tuple[29])
self.BrokerFee=float(i_tuple[30])
self.Message=self._to_bytes(i_tuple[31])
self.Digest=self._to_bytes(i_tuple[32])
self.BankAccType=self._to_bytes(i_tuple[33])
self.DeviceID=self._to_bytes(i_tuple[34])
self.BankSecuAccType=self._to_bytes(i_tuple[35])
self.BrokerIDByBank=self._to_bytes(i_tuple[36])
self.BankSecuAcc=self._to_bytes(i_tuple[37])
self.BankPwdFlag=self._to_bytes(i_tuple[38])
self.SecuPwdFlag=self._to_bytes(i_tuple[39])
self.OperNo=self._to_bytes(i_tuple[40])
self.RequestID=int(i_tuple[41])
self.TID=int(i_tuple[42])
self.TransferStatus=self._to_bytes(i_tuple[43])
self.LongCustomerName=self._to_bytes(i_tuple[44])
class RspTransferField(Base):
"""银行发起银行资金转期货响应"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('CustomerName',ctypes.c_char*51)# 客户姓名
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('CustType',ctypes.c_char)# 客户类型
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankPassWord',ctypes.c_char*41)# 银行密码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 期货密码
,('InstallID',ctypes.c_int)# 安装编号
,('FutureSerial',ctypes.c_int)# 期货公司流水号
,('UserID',ctypes.c_char*16)# 用户标识
,('VerifyCertNoFlag',ctypes.c_char)# 验证客户证件号码标志
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('TradeAmount',ctypes.c_double)# 转帐金额
,('FutureFetchAmount',ctypes.c_double)# 期货可取金额
,('FeePayFlag',ctypes.c_char)# 费用支付标志
,('CustFee',ctypes.c_double)# 应收客户费用
,('BrokerFee',ctypes.c_double)# 应收期货公司费用
,('Message',ctypes.c_char*129)# 发送方给接收方的消息
,('Digest',ctypes.c_char*36)# 摘要
,('BankAccType',ctypes.c_char)# 银行帐号类型
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BankSecuAccType',ctypes.c_char)# 期货单位帐号类型
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('BankSecuAcc',ctypes.c_char*41)# 期货单位帐号
,('BankPwdFlag',ctypes.c_char)# 银行密码标志
,('SecuPwdFlag',ctypes.c_char)# 期货资金密码核对标志
,('OperNo',ctypes.c_char*17)# 交易柜员
,('RequestID',ctypes.c_int)# 请求编号
,('TID',ctypes.c_int)# 交易ID
,('TransferStatus',ctypes.c_char)# 转账交易状态
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
,('LongCustomerName',ctypes.c_char*161)# 长客户姓名
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,CustomerName='',IdCardType='',IdentifiedCardNo='',CustType='',BankAccount='',BankPassWord='',AccountID='',Password='',InstallID=0,FutureSerial=0,UserID='',VerifyCertNoFlag='',CurrencyID='',TradeAmount=0.0,FutureFetchAmount=0.0,FeePayFlag='',CustFee=0.0,BrokerFee=0.0,Message='',Digest='',BankAccType='',DeviceID='',BankSecuAccType='',BrokerIDByBank='',BankSecuAcc='',BankPwdFlag='',SecuPwdFlag='',OperNo='',RequestID=0,TID=0,TransferStatus='',ErrorID=0,ErrorMsg='',LongCustomerName=''):
super(RspTransferField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.CustomerName=self._to_bytes(CustomerName)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.CustType=self._to_bytes(CustType)
self.BankAccount=self._to_bytes(BankAccount)
self.BankPassWord=self._to_bytes(BankPassWord)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.InstallID=int(InstallID)
self.FutureSerial=int(FutureSerial)
self.UserID=self._to_bytes(UserID)
self.VerifyCertNoFlag=self._to_bytes(VerifyCertNoFlag)
self.CurrencyID=self._to_bytes(CurrencyID)
self.TradeAmount=float(TradeAmount)
self.FutureFetchAmount=float(FutureFetchAmount)
self.FeePayFlag=self._to_bytes(FeePayFlag)
self.CustFee=float(CustFee)
self.BrokerFee=float(BrokerFee)
self.Message=self._to_bytes(Message)
self.Digest=self._to_bytes(Digest)
self.BankAccType=self._to_bytes(BankAccType)
self.DeviceID=self._to_bytes(DeviceID)
self.BankSecuAccType=self._to_bytes(BankSecuAccType)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.BankSecuAcc=self._to_bytes(BankSecuAcc)
self.BankPwdFlag=self._to_bytes(BankPwdFlag)
self.SecuPwdFlag=self._to_bytes(SecuPwdFlag)
self.OperNo=self._to_bytes(OperNo)
self.RequestID=int(RequestID)
self.TID=int(TID)
self.TransferStatus=self._to_bytes(TransferStatus)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
self.LongCustomerName=self._to_bytes(LongCustomerName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.CustomerName=self._to_bytes(i_tuple[13])
self.IdCardType=self._to_bytes(i_tuple[14])
self.IdentifiedCardNo=self._to_bytes(i_tuple[15])
self.CustType=self._to_bytes(i_tuple[16])
self.BankAccount=self._to_bytes(i_tuple[17])
self.BankPassWord=self._to_bytes(i_tuple[18])
self.AccountID=self._to_bytes(i_tuple[19])
self.Password=self._to_bytes(i_tuple[20])
self.InstallID=int(i_tuple[21])
self.FutureSerial=int(i_tuple[22])
self.UserID=self._to_bytes(i_tuple[23])
self.VerifyCertNoFlag=self._to_bytes(i_tuple[24])
self.CurrencyID=self._to_bytes(i_tuple[25])
self.TradeAmount=float(i_tuple[26])
self.FutureFetchAmount=float(i_tuple[27])
self.FeePayFlag=self._to_bytes(i_tuple[28])
self.CustFee=float(i_tuple[29])
self.BrokerFee=float(i_tuple[30])
self.Message=self._to_bytes(i_tuple[31])
self.Digest=self._to_bytes(i_tuple[32])
self.BankAccType=self._to_bytes(i_tuple[33])
self.DeviceID=self._to_bytes(i_tuple[34])
self.BankSecuAccType=self._to_bytes(i_tuple[35])
self.BrokerIDByBank=self._to_bytes(i_tuple[36])
self.BankSecuAcc=self._to_bytes(i_tuple[37])
self.BankPwdFlag=self._to_bytes(i_tuple[38])
self.SecuPwdFlag=self._to_bytes(i_tuple[39])
self.OperNo=self._to_bytes(i_tuple[40])
self.RequestID=int(i_tuple[41])
self.TID=int(i_tuple[42])
self.TransferStatus=self._to_bytes(i_tuple[43])
self.ErrorID=int(i_tuple[44])
self.ErrorMsg=self._to_bytes(i_tuple[45])
self.LongCustomerName=self._to_bytes(i_tuple[46])
class ReqRepealField(Base):
"""冲正请求"""
_fields_ = [
('RepealTimeInterval',ctypes.c_int)# ///冲正时间间隔
,('RepealedTimes',ctypes.c_int)# 已经冲正次数
,('BankRepealFlag',ctypes.c_char)# 银行冲正标志
,('BrokerRepealFlag',ctypes.c_char)# 期商冲正标志
,('PlateRepealSerial',ctypes.c_int)# 被冲正平台流水号
,('BankRepealSerial',ctypes.c_char*13)# 被冲正银行流水号
,('FutureRepealSerial',ctypes.c_int)# 被冲正期货流水号
,('TradeCode',ctypes.c_char*7)# 业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('CustomerName',ctypes.c_char*51)# 客户姓名
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('CustType',ctypes.c_char)# 客户类型
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankPassWord',ctypes.c_char*41)# 银行密码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 期货密码
,('InstallID',ctypes.c_int)# 安装编号
,('FutureSerial',ctypes.c_int)# 期货公司流水号
,('UserID',ctypes.c_char*16)# 用户标识
,('VerifyCertNoFlag',ctypes.c_char)# 验证客户证件号码标志
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('TradeAmount',ctypes.c_double)# 转帐金额
,('FutureFetchAmount',ctypes.c_double)# 期货可取金额
,('FeePayFlag',ctypes.c_char)# 费用支付标志
,('CustFee',ctypes.c_double)# 应收客户费用
,('BrokerFee',ctypes.c_double)# 应收期货公司费用
,('Message',ctypes.c_char*129)# 发送方给接收方的消息
,('Digest',ctypes.c_char*36)# 摘要
,('BankAccType',ctypes.c_char)# 银行帐号类型
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BankSecuAccType',ctypes.c_char)# 期货单位帐号类型
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('BankSecuAcc',ctypes.c_char*41)# 期货单位帐号
,('BankPwdFlag',ctypes.c_char)# 银行密码标志
,('SecuPwdFlag',ctypes.c_char)# 期货资金密码核对标志
,('OperNo',ctypes.c_char*17)# 交易柜员
,('RequestID',ctypes.c_int)# 请求编号
,('TID',ctypes.c_int)# 交易ID
,('TransferStatus',ctypes.c_char)# 转账交易状态
,('LongCustomerName',ctypes.c_char*161)# 长客户姓名
]
def __init__(self,RepealTimeInterval= 0,RepealedTimes=0,BankRepealFlag='',BrokerRepealFlag='',PlateRepealSerial=0,BankRepealSerial='',FutureRepealSerial=0,TradeCode='',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,CustomerName='',IdCardType='',IdentifiedCardNo='',CustType='',BankAccount='',BankPassWord='',AccountID='',Password='',InstallID=0,FutureSerial=0,UserID='',VerifyCertNoFlag='',CurrencyID='',TradeAmount=0.0,FutureFetchAmount=0.0,FeePayFlag='',CustFee=0.0,BrokerFee=0.0,Message='',Digest='',BankAccType='',DeviceID='',BankSecuAccType='',BrokerIDByBank='',BankSecuAcc='',BankPwdFlag='',SecuPwdFlag='',OperNo='',RequestID=0,TID=0,TransferStatus='',LongCustomerName=''):
super(ReqRepealField,self).__init__()
self.RepealTimeInterval=int(RepealTimeInterval)
self.RepealedTimes=int(RepealedTimes)
self.BankRepealFlag=self._to_bytes(BankRepealFlag)
self.BrokerRepealFlag=self._to_bytes(BrokerRepealFlag)
self.PlateRepealSerial=int(PlateRepealSerial)
self.BankRepealSerial=self._to_bytes(BankRepealSerial)
self.FutureRepealSerial=int(FutureRepealSerial)
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.CustomerName=self._to_bytes(CustomerName)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.CustType=self._to_bytes(CustType)
self.BankAccount=self._to_bytes(BankAccount)
self.BankPassWord=self._to_bytes(BankPassWord)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.InstallID=int(InstallID)
self.FutureSerial=int(FutureSerial)
self.UserID=self._to_bytes(UserID)
self.VerifyCertNoFlag=self._to_bytes(VerifyCertNoFlag)
self.CurrencyID=self._to_bytes(CurrencyID)
self.TradeAmount=float(TradeAmount)
self.FutureFetchAmount=float(FutureFetchAmount)
self.FeePayFlag=self._to_bytes(FeePayFlag)
self.CustFee=float(CustFee)
self.BrokerFee=float(BrokerFee)
self.Message=self._to_bytes(Message)
self.Digest=self._to_bytes(Digest)
self.BankAccType=self._to_bytes(BankAccType)
self.DeviceID=self._to_bytes(DeviceID)
self.BankSecuAccType=self._to_bytes(BankSecuAccType)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.BankSecuAcc=self._to_bytes(BankSecuAcc)
self.BankPwdFlag=self._to_bytes(BankPwdFlag)
self.SecuPwdFlag=self._to_bytes(SecuPwdFlag)
self.OperNo=self._to_bytes(OperNo)
self.RequestID=int(RequestID)
self.TID=int(TID)
self.TransferStatus=self._to_bytes(TransferStatus)
self.LongCustomerName=self._to_bytes(LongCustomerName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.RepealTimeInterval=int(i_tuple[1])
self.RepealedTimes=int(i_tuple[2])
self.BankRepealFlag=self._to_bytes(i_tuple[3])
self.BrokerRepealFlag=self._to_bytes(i_tuple[4])
self.PlateRepealSerial=int(i_tuple[5])
self.BankRepealSerial=self._to_bytes(i_tuple[6])
self.FutureRepealSerial=int(i_tuple[7])
self.TradeCode=self._to_bytes(i_tuple[8])
self.BankID=self._to_bytes(i_tuple[9])
self.BankBranchID=self._to_bytes(i_tuple[10])
self.BrokerID=self._to_bytes(i_tuple[11])
self.BrokerBranchID=self._to_bytes(i_tuple[12])
self.TradeDate=self._to_bytes(i_tuple[13])
self.TradeTime=self._to_bytes(i_tuple[14])
self.BankSerial=self._to_bytes(i_tuple[15])
self.TradingDay=self._to_bytes(i_tuple[16])
self.PlateSerial=int(i_tuple[17])
self.LastFragment=self._to_bytes(i_tuple[18])
self.SessionID=int(i_tuple[19])
self.CustomerName=self._to_bytes(i_tuple[20])
self.IdCardType=self._to_bytes(i_tuple[21])
self.IdentifiedCardNo=self._to_bytes(i_tuple[22])
self.CustType=self._to_bytes(i_tuple[23])
self.BankAccount=self._to_bytes(i_tuple[24])
self.BankPassWord=self._to_bytes(i_tuple[25])
self.AccountID=self._to_bytes(i_tuple[26])
self.Password=self._to_bytes(i_tuple[27])
self.InstallID=int(i_tuple[28])
self.FutureSerial=int(i_tuple[29])
self.UserID=self._to_bytes(i_tuple[30])
self.VerifyCertNoFlag=self._to_bytes(i_tuple[31])
self.CurrencyID=self._to_bytes(i_tuple[32])
self.TradeAmount=float(i_tuple[33])
self.FutureFetchAmount=float(i_tuple[34])
self.FeePayFlag=self._to_bytes(i_tuple[35])
self.CustFee=float(i_tuple[36])
self.BrokerFee=float(i_tuple[37])
self.Message=self._to_bytes(i_tuple[38])
self.Digest=self._to_bytes(i_tuple[39])
self.BankAccType=self._to_bytes(i_tuple[40])
self.DeviceID=self._to_bytes(i_tuple[41])
self.BankSecuAccType=self._to_bytes(i_tuple[42])
self.BrokerIDByBank=self._to_bytes(i_tuple[43])
self.BankSecuAcc=self._to_bytes(i_tuple[44])
self.BankPwdFlag=self._to_bytes(i_tuple[45])
self.SecuPwdFlag=self._to_bytes(i_tuple[46])
self.OperNo=self._to_bytes(i_tuple[47])
self.RequestID=int(i_tuple[48])
self.TID=int(i_tuple[49])
self.TransferStatus=self._to_bytes(i_tuple[50])
self.LongCustomerName=self._to_bytes(i_tuple[51])
class RspRepealField(Base):
"""冲正响应"""
_fields_ = [
('RepealTimeInterval',ctypes.c_int)# ///冲正时间间隔
,('RepealedTimes',ctypes.c_int)# 已经冲正次数
,('BankRepealFlag',ctypes.c_char)# 银行冲正标志
,('BrokerRepealFlag',ctypes.c_char)# 期商冲正标志
,('PlateRepealSerial',ctypes.c_int)# 被冲正平台流水号
,('BankRepealSerial',ctypes.c_char*13)# 被冲正银行流水号
,('FutureRepealSerial',ctypes.c_int)# 被冲正期货流水号
,('TradeCode',ctypes.c_char*7)# 业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('CustomerName',ctypes.c_char*51)# 客户姓名
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('CustType',ctypes.c_char)# 客户类型
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankPassWord',ctypes.c_char*41)# 银行密码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 期货密码
,('InstallID',ctypes.c_int)# 安装编号
,('FutureSerial',ctypes.c_int)# 期货公司流水号
,('UserID',ctypes.c_char*16)# 用户标识
,('VerifyCertNoFlag',ctypes.c_char)# 验证客户证件号码标志
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('TradeAmount',ctypes.c_double)# 转帐金额
,('FutureFetchAmount',ctypes.c_double)# 期货可取金额
,('FeePayFlag',ctypes.c_char)# 费用支付标志
,('CustFee',ctypes.c_double)# 应收客户费用
,('BrokerFee',ctypes.c_double)# 应收期货公司费用
,('Message',ctypes.c_char*129)# 发送方给接收方的消息
,('Digest',ctypes.c_char*36)# 摘要
,('BankAccType',ctypes.c_char)# 银行帐号类型
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BankSecuAccType',ctypes.c_char)# 期货单位帐号类型
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('BankSecuAcc',ctypes.c_char*41)# 期货单位帐号
,('BankPwdFlag',ctypes.c_char)# 银行密码标志
,('SecuPwdFlag',ctypes.c_char)# 期货资金密码核对标志
,('OperNo',ctypes.c_char*17)# 交易柜员
,('RequestID',ctypes.c_int)# 请求编号
,('TID',ctypes.c_int)# 交易ID
,('TransferStatus',ctypes.c_char)# 转账交易状态
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
,('LongCustomerName',ctypes.c_char*161)# 长客户姓名
]
def __init__(self,RepealTimeInterval= 0,RepealedTimes=0,BankRepealFlag='',BrokerRepealFlag='',PlateRepealSerial=0,BankRepealSerial='',FutureRepealSerial=0,TradeCode='',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,CustomerName='',IdCardType='',IdentifiedCardNo='',CustType='',BankAccount='',BankPassWord='',AccountID='',Password='',InstallID=0,FutureSerial=0,UserID='',VerifyCertNoFlag='',CurrencyID='',TradeAmount=0.0,FutureFetchAmount=0.0,FeePayFlag='',CustFee=0.0,BrokerFee=0.0,Message='',Digest='',BankAccType='',DeviceID='',BankSecuAccType='',BrokerIDByBank='',BankSecuAcc='',BankPwdFlag='',SecuPwdFlag='',OperNo='',RequestID=0,TID=0,TransferStatus='',ErrorID=0,ErrorMsg='',LongCustomerName=''):
super(RspRepealField,self).__init__()
self.RepealTimeInterval=int(RepealTimeInterval)
self.RepealedTimes=int(RepealedTimes)
self.BankRepealFlag=self._to_bytes(BankRepealFlag)
self.BrokerRepealFlag=self._to_bytes(BrokerRepealFlag)
self.PlateRepealSerial=int(PlateRepealSerial)
self.BankRepealSerial=self._to_bytes(BankRepealSerial)
self.FutureRepealSerial=int(FutureRepealSerial)
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.CustomerName=self._to_bytes(CustomerName)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.CustType=self._to_bytes(CustType)
self.BankAccount=self._to_bytes(BankAccount)
self.BankPassWord=self._to_bytes(BankPassWord)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.InstallID=int(InstallID)
self.FutureSerial=int(FutureSerial)
self.UserID=self._to_bytes(UserID)
self.VerifyCertNoFlag=self._to_bytes(VerifyCertNoFlag)
self.CurrencyID=self._to_bytes(CurrencyID)
self.TradeAmount=float(TradeAmount)
self.FutureFetchAmount=float(FutureFetchAmount)
self.FeePayFlag=self._to_bytes(FeePayFlag)
self.CustFee=float(CustFee)
self.BrokerFee=float(BrokerFee)
self.Message=self._to_bytes(Message)
self.Digest=self._to_bytes(Digest)
self.BankAccType=self._to_bytes(BankAccType)
self.DeviceID=self._to_bytes(DeviceID)
self.BankSecuAccType=self._to_bytes(BankSecuAccType)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.BankSecuAcc=self._to_bytes(BankSecuAcc)
self.BankPwdFlag=self._to_bytes(BankPwdFlag)
self.SecuPwdFlag=self._to_bytes(SecuPwdFlag)
self.OperNo=self._to_bytes(OperNo)
self.RequestID=int(RequestID)
self.TID=int(TID)
self.TransferStatus=self._to_bytes(TransferStatus)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
self.LongCustomerName=self._to_bytes(LongCustomerName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.RepealTimeInterval=int(i_tuple[1])
self.RepealedTimes=int(i_tuple[2])
self.BankRepealFlag=self._to_bytes(i_tuple[3])
self.BrokerRepealFlag=self._to_bytes(i_tuple[4])
self.PlateRepealSerial=int(i_tuple[5])
self.BankRepealSerial=self._to_bytes(i_tuple[6])
self.FutureRepealSerial=int(i_tuple[7])
self.TradeCode=self._to_bytes(i_tuple[8])
self.BankID=self._to_bytes(i_tuple[9])
self.BankBranchID=self._to_bytes(i_tuple[10])
self.BrokerID=self._to_bytes(i_tuple[11])
self.BrokerBranchID=self._to_bytes(i_tuple[12])
self.TradeDate=self._to_bytes(i_tuple[13])
self.TradeTime=self._to_bytes(i_tuple[14])
self.BankSerial=self._to_bytes(i_tuple[15])
self.TradingDay=self._to_bytes(i_tuple[16])
self.PlateSerial=int(i_tuple[17])
self.LastFragment=self._to_bytes(i_tuple[18])
self.SessionID=int(i_tuple[19])
self.CustomerName=self._to_bytes(i_tuple[20])
self.IdCardType=self._to_bytes(i_tuple[21])
self.IdentifiedCardNo=self._to_bytes(i_tuple[22])
self.CustType=self._to_bytes(i_tuple[23])
self.BankAccount=self._to_bytes(i_tuple[24])
self.BankPassWord=self._to_bytes(i_tuple[25])
self.AccountID=self._to_bytes(i_tuple[26])
self.Password=self._to_bytes(i_tuple[27])
self.InstallID=int(i_tuple[28])
self.FutureSerial=int(i_tuple[29])
self.UserID=self._to_bytes(i_tuple[30])
self.VerifyCertNoFlag=self._to_bytes(i_tuple[31])
self.CurrencyID=self._to_bytes(i_tuple[32])
self.TradeAmount=float(i_tuple[33])
self.FutureFetchAmount=float(i_tuple[34])
self.FeePayFlag=self._to_bytes(i_tuple[35])
self.CustFee=float(i_tuple[36])
self.BrokerFee=float(i_tuple[37])
self.Message=self._to_bytes(i_tuple[38])
self.Digest=self._to_bytes(i_tuple[39])
self.BankAccType=self._to_bytes(i_tuple[40])
self.DeviceID=self._to_bytes(i_tuple[41])
self.BankSecuAccType=self._to_bytes(i_tuple[42])
self.BrokerIDByBank=self._to_bytes(i_tuple[43])
self.BankSecuAcc=self._to_bytes(i_tuple[44])
self.BankPwdFlag=self._to_bytes(i_tuple[45])
self.SecuPwdFlag=self._to_bytes(i_tuple[46])
self.OperNo=self._to_bytes(i_tuple[47])
self.RequestID=int(i_tuple[48])
self.TID=int(i_tuple[49])
self.TransferStatus=self._to_bytes(i_tuple[50])
self.ErrorID=int(i_tuple[51])
self.ErrorMsg=self._to_bytes(i_tuple[52])
self.LongCustomerName=self._to_bytes(i_tuple[53])
class ReqQueryAccountField(Base):
"""查询账户信息请求"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('CustomerName',ctypes.c_char*51)# 客户姓名
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('CustType',ctypes.c_char)# 客户类型
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankPassWord',ctypes.c_char*41)# 银行密码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 期货密码
,('FutureSerial',ctypes.c_int)# 期货公司流水号
,('InstallID',ctypes.c_int)# 安装编号
,('UserID',ctypes.c_char*16)# 用户标识
,('VerifyCertNoFlag',ctypes.c_char)# 验证客户证件号码标志
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('Digest',ctypes.c_char*36)# 摘要
,('BankAccType',ctypes.c_char)# 银行帐号类型
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BankSecuAccType',ctypes.c_char)# 期货单位帐号类型
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('BankSecuAcc',ctypes.c_char*41)# 期货单位帐号
,('BankPwdFlag',ctypes.c_char)# 银行密码标志
,('SecuPwdFlag',ctypes.c_char)# 期货资金密码核对标志
,('OperNo',ctypes.c_char*17)# 交易柜员
,('RequestID',ctypes.c_int)# 请求编号
,('TID',ctypes.c_int)# 交易ID
,('LongCustomerName',ctypes.c_char*161)# 长客户姓名
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,CustomerName='',IdCardType='',IdentifiedCardNo='',CustType='',BankAccount='',BankPassWord='',AccountID='',Password='',FutureSerial=0,InstallID=0,UserID='',VerifyCertNoFlag='',CurrencyID='',Digest='',BankAccType='',DeviceID='',BankSecuAccType='',BrokerIDByBank='',BankSecuAcc='',BankPwdFlag='',SecuPwdFlag='',OperNo='',RequestID=0,TID=0,LongCustomerName=''):
super(ReqQueryAccountField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.CustomerName=self._to_bytes(CustomerName)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.CustType=self._to_bytes(CustType)
self.BankAccount=self._to_bytes(BankAccount)
self.BankPassWord=self._to_bytes(BankPassWord)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.FutureSerial=int(FutureSerial)
self.InstallID=int(InstallID)
self.UserID=self._to_bytes(UserID)
self.VerifyCertNoFlag=self._to_bytes(VerifyCertNoFlag)
self.CurrencyID=self._to_bytes(CurrencyID)
self.Digest=self._to_bytes(Digest)
self.BankAccType=self._to_bytes(BankAccType)
self.DeviceID=self._to_bytes(DeviceID)
self.BankSecuAccType=self._to_bytes(BankSecuAccType)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.BankSecuAcc=self._to_bytes(BankSecuAcc)
self.BankPwdFlag=self._to_bytes(BankPwdFlag)
self.SecuPwdFlag=self._to_bytes(SecuPwdFlag)
self.OperNo=self._to_bytes(OperNo)
self.RequestID=int(RequestID)
self.TID=int(TID)
self.LongCustomerName=self._to_bytes(LongCustomerName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.CustomerName=self._to_bytes(i_tuple[13])
self.IdCardType=self._to_bytes(i_tuple[14])
self.IdentifiedCardNo=self._to_bytes(i_tuple[15])
self.CustType=self._to_bytes(i_tuple[16])
self.BankAccount=self._to_bytes(i_tuple[17])
self.BankPassWord=self._to_bytes(i_tuple[18])
self.AccountID=self._to_bytes(i_tuple[19])
self.Password=self._to_bytes(i_tuple[20])
self.FutureSerial=int(i_tuple[21])
self.InstallID=int(i_tuple[22])
self.UserID=self._to_bytes(i_tuple[23])
self.VerifyCertNoFlag=self._to_bytes(i_tuple[24])
self.CurrencyID=self._to_bytes(i_tuple[25])
self.Digest=self._to_bytes(i_tuple[26])
self.BankAccType=self._to_bytes(i_tuple[27])
self.DeviceID=self._to_bytes(i_tuple[28])
self.BankSecuAccType=self._to_bytes(i_tuple[29])
self.BrokerIDByBank=self._to_bytes(i_tuple[30])
self.BankSecuAcc=self._to_bytes(i_tuple[31])
self.BankPwdFlag=self._to_bytes(i_tuple[32])
self.SecuPwdFlag=self._to_bytes(i_tuple[33])
self.OperNo=self._to_bytes(i_tuple[34])
self.RequestID=int(i_tuple[35])
self.TID=int(i_tuple[36])
self.LongCustomerName=self._to_bytes(i_tuple[37])
class RspQueryAccountField(Base):
"""查询账户信息响应"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('CustomerName',ctypes.c_char*51)# 客户姓名
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('CustType',ctypes.c_char)# 客户类型
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankPassWord',ctypes.c_char*41)# 银行密码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 期货密码
,('FutureSerial',ctypes.c_int)# 期货公司流水号
,('InstallID',ctypes.c_int)# 安装编号
,('UserID',ctypes.c_char*16)# 用户标识
,('VerifyCertNoFlag',ctypes.c_char)# 验证客户证件号码标志
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('Digest',ctypes.c_char*36)# 摘要
,('BankAccType',ctypes.c_char)# 银行帐号类型
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BankSecuAccType',ctypes.c_char)# 期货单位帐号类型
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('BankSecuAcc',ctypes.c_char*41)# 期货单位帐号
,('BankPwdFlag',ctypes.c_char)# 银行密码标志
,('SecuPwdFlag',ctypes.c_char)# 期货资金密码核对标志
,('OperNo',ctypes.c_char*17)# 交易柜员
,('RequestID',ctypes.c_int)# 请求编号
,('TID',ctypes.c_int)# 交易ID
,('BankUseAmount',ctypes.c_double)# 银行可用金额
,('BankFetchAmount',ctypes.c_double)# 银行可取金额
,('LongCustomerName',ctypes.c_char*161)# 长客户姓名
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,CustomerName='',IdCardType='',IdentifiedCardNo='',CustType='',BankAccount='',BankPassWord='',AccountID='',Password='',FutureSerial=0,InstallID=0,UserID='',VerifyCertNoFlag='',CurrencyID='',Digest='',BankAccType='',DeviceID='',BankSecuAccType='',BrokerIDByBank='',BankSecuAcc='',BankPwdFlag='',SecuPwdFlag='',OperNo='',RequestID=0,TID=0,BankUseAmount=0.0,BankFetchAmount=0.0,LongCustomerName=''):
super(RspQueryAccountField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.CustomerName=self._to_bytes(CustomerName)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.CustType=self._to_bytes(CustType)
self.BankAccount=self._to_bytes(BankAccount)
self.BankPassWord=self._to_bytes(BankPassWord)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.FutureSerial=int(FutureSerial)
self.InstallID=int(InstallID)
self.UserID=self._to_bytes(UserID)
self.VerifyCertNoFlag=self._to_bytes(VerifyCertNoFlag)
self.CurrencyID=self._to_bytes(CurrencyID)
self.Digest=self._to_bytes(Digest)
self.BankAccType=self._to_bytes(BankAccType)
self.DeviceID=self._to_bytes(DeviceID)
self.BankSecuAccType=self._to_bytes(BankSecuAccType)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.BankSecuAcc=self._to_bytes(BankSecuAcc)
self.BankPwdFlag=self._to_bytes(BankPwdFlag)
self.SecuPwdFlag=self._to_bytes(SecuPwdFlag)
self.OperNo=self._to_bytes(OperNo)
self.RequestID=int(RequestID)
self.TID=int(TID)
self.BankUseAmount=float(BankUseAmount)
self.BankFetchAmount=float(BankFetchAmount)
self.LongCustomerName=self._to_bytes(LongCustomerName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.CustomerName=self._to_bytes(i_tuple[13])
self.IdCardType=self._to_bytes(i_tuple[14])
self.IdentifiedCardNo=self._to_bytes(i_tuple[15])
self.CustType=self._to_bytes(i_tuple[16])
self.BankAccount=self._to_bytes(i_tuple[17])
self.BankPassWord=self._to_bytes(i_tuple[18])
self.AccountID=self._to_bytes(i_tuple[19])
self.Password=self._to_bytes(i_tuple[20])
self.FutureSerial=int(i_tuple[21])
self.InstallID=int(i_tuple[22])
self.UserID=self._to_bytes(i_tuple[23])
self.VerifyCertNoFlag=self._to_bytes(i_tuple[24])
self.CurrencyID=self._to_bytes(i_tuple[25])
self.Digest=self._to_bytes(i_tuple[26])
self.BankAccType=self._to_bytes(i_tuple[27])
self.DeviceID=self._to_bytes(i_tuple[28])
self.BankSecuAccType=self._to_bytes(i_tuple[29])
self.BrokerIDByBank=self._to_bytes(i_tuple[30])
self.BankSecuAcc=self._to_bytes(i_tuple[31])
self.BankPwdFlag=self._to_bytes(i_tuple[32])
self.SecuPwdFlag=self._to_bytes(i_tuple[33])
self.OperNo=self._to_bytes(i_tuple[34])
self.RequestID=int(i_tuple[35])
self.TID=int(i_tuple[36])
self.BankUseAmount=float(i_tuple[37])
self.BankFetchAmount=float(i_tuple[38])
self.LongCustomerName=self._to_bytes(i_tuple[39])
class FutureSignIOField(Base):
"""期商签到签退"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('InstallID',ctypes.c_int)# 安装编号
,('UserID',ctypes.c_char*16)# 用户标识
,('Digest',ctypes.c_char*36)# 摘要
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('OperNo',ctypes.c_char*17)# 交易柜员
,('RequestID',ctypes.c_int)# 请求编号
,('TID',ctypes.c_int)# 交易ID
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,InstallID=0,UserID='',Digest='',CurrencyID='',DeviceID='',BrokerIDByBank='',OperNo='',RequestID=0,TID=0):
super(FutureSignIOField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.InstallID=int(InstallID)
self.UserID=self._to_bytes(UserID)
self.Digest=self._to_bytes(Digest)
self.CurrencyID=self._to_bytes(CurrencyID)
self.DeviceID=self._to_bytes(DeviceID)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.OperNo=self._to_bytes(OperNo)
self.RequestID=int(RequestID)
self.TID=int(TID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.InstallID=int(i_tuple[13])
self.UserID=self._to_bytes(i_tuple[14])
self.Digest=self._to_bytes(i_tuple[15])
self.CurrencyID=self._to_bytes(i_tuple[16])
self.DeviceID=self._to_bytes(i_tuple[17])
self.BrokerIDByBank=self._to_bytes(i_tuple[18])
self.OperNo=self._to_bytes(i_tuple[19])
self.RequestID=int(i_tuple[20])
self.TID=int(i_tuple[21])
class RspFutureSignInField(Base):
"""期商签到响应"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('InstallID',ctypes.c_int)# 安装编号
,('UserID',ctypes.c_char*16)# 用户标识
,('Digest',ctypes.c_char*36)# 摘要
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('OperNo',ctypes.c_char*17)# 交易柜员
,('RequestID',ctypes.c_int)# 请求编号
,('TID',ctypes.c_int)# 交易ID
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
,('PinKey',ctypes.c_char*129)# PIN密钥
,('MacKey',ctypes.c_char*129)# MAC密钥
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,InstallID=0,UserID='',Digest='',CurrencyID='',DeviceID='',BrokerIDByBank='',OperNo='',RequestID=0,TID=0,ErrorID=0,ErrorMsg='',PinKey='',MacKey=''):
super(RspFutureSignInField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.InstallID=int(InstallID)
self.UserID=self._to_bytes(UserID)
self.Digest=self._to_bytes(Digest)
self.CurrencyID=self._to_bytes(CurrencyID)
self.DeviceID=self._to_bytes(DeviceID)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.OperNo=self._to_bytes(OperNo)
self.RequestID=int(RequestID)
self.TID=int(TID)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
self.PinKey=self._to_bytes(PinKey)
self.MacKey=self._to_bytes(MacKey)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.InstallID=int(i_tuple[13])
self.UserID=self._to_bytes(i_tuple[14])
self.Digest=self._to_bytes(i_tuple[15])
self.CurrencyID=self._to_bytes(i_tuple[16])
self.DeviceID=self._to_bytes(i_tuple[17])
self.BrokerIDByBank=self._to_bytes(i_tuple[18])
self.OperNo=self._to_bytes(i_tuple[19])
self.RequestID=int(i_tuple[20])
self.TID=int(i_tuple[21])
self.ErrorID=int(i_tuple[22])
self.ErrorMsg=self._to_bytes(i_tuple[23])
self.PinKey=self._to_bytes(i_tuple[24])
self.MacKey=self._to_bytes(i_tuple[25])
class ReqFutureSignOutField(Base):
"""期商签退请求"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('InstallID',ctypes.c_int)# 安装编号
,('UserID',ctypes.c_char*16)# 用户标识
,('Digest',ctypes.c_char*36)# 摘要
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('OperNo',ctypes.c_char*17)# 交易柜员
,('RequestID',ctypes.c_int)# 请求编号
,('TID',ctypes.c_int)# 交易ID
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,InstallID=0,UserID='',Digest='',CurrencyID='',DeviceID='',BrokerIDByBank='',OperNo='',RequestID=0,TID=0):
super(ReqFutureSignOutField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.InstallID=int(InstallID)
self.UserID=self._to_bytes(UserID)
self.Digest=self._to_bytes(Digest)
self.CurrencyID=self._to_bytes(CurrencyID)
self.DeviceID=self._to_bytes(DeviceID)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.OperNo=self._to_bytes(OperNo)
self.RequestID=int(RequestID)
self.TID=int(TID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.InstallID=int(i_tuple[13])
self.UserID=self._to_bytes(i_tuple[14])
self.Digest=self._to_bytes(i_tuple[15])
self.CurrencyID=self._to_bytes(i_tuple[16])
self.DeviceID=self._to_bytes(i_tuple[17])
self.BrokerIDByBank=self._to_bytes(i_tuple[18])
self.OperNo=self._to_bytes(i_tuple[19])
self.RequestID=int(i_tuple[20])
self.TID=int(i_tuple[21])
class RspFutureSignOutField(Base):
"""期商签退响应"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('InstallID',ctypes.c_int)# 安装编号
,('UserID',ctypes.c_char*16)# 用户标识
,('Digest',ctypes.c_char*36)# 摘要
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('OperNo',ctypes.c_char*17)# 交易柜员
,('RequestID',ctypes.c_int)# 请求编号
,('TID',ctypes.c_int)# 交易ID
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,InstallID=0,UserID='',Digest='',CurrencyID='',DeviceID='',BrokerIDByBank='',OperNo='',RequestID=0,TID=0,ErrorID=0,ErrorMsg=''):
super(RspFutureSignOutField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.InstallID=int(InstallID)
self.UserID=self._to_bytes(UserID)
self.Digest=self._to_bytes(Digest)
self.CurrencyID=self._to_bytes(CurrencyID)
self.DeviceID=self._to_bytes(DeviceID)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.OperNo=self._to_bytes(OperNo)
self.RequestID=int(RequestID)
self.TID=int(TID)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.InstallID=int(i_tuple[13])
self.UserID=self._to_bytes(i_tuple[14])
self.Digest=self._to_bytes(i_tuple[15])
self.CurrencyID=self._to_bytes(i_tuple[16])
self.DeviceID=self._to_bytes(i_tuple[17])
self.BrokerIDByBank=self._to_bytes(i_tuple[18])
self.OperNo=self._to_bytes(i_tuple[19])
self.RequestID=int(i_tuple[20])
self.TID=int(i_tuple[21])
self.ErrorID=int(i_tuple[22])
self.ErrorMsg=self._to_bytes(i_tuple[23])
class ReqQueryTradeResultBySerialField(Base):
"""查询指定流水号的交易结果请求"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('Reference',ctypes.c_int)# 流水号
,('RefrenceIssureType',ctypes.c_char)# 本流水号发布者的机构类型
,('RefrenceIssure',ctypes.c_char*36)# 本流水号发布者机构编码
,('CustomerName',ctypes.c_char*51)# 客户姓名
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('CustType',ctypes.c_char)# 客户类型
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankPassWord',ctypes.c_char*41)# 银行密码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 期货密码
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('TradeAmount',ctypes.c_double)# 转帐金额
,('Digest',ctypes.c_char*36)# 摘要
,('LongCustomerName',ctypes.c_char*161)# 长客户姓名
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,Reference=0,RefrenceIssureType='',RefrenceIssure='',CustomerName='',IdCardType='',IdentifiedCardNo='',CustType='',BankAccount='',BankPassWord='',AccountID='',Password='',CurrencyID='',TradeAmount=0.0,Digest='',LongCustomerName=''):
super(ReqQueryTradeResultBySerialField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.Reference=int(Reference)
self.RefrenceIssureType=self._to_bytes(RefrenceIssureType)
self.RefrenceIssure=self._to_bytes(RefrenceIssure)
self.CustomerName=self._to_bytes(CustomerName)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.CustType=self._to_bytes(CustType)
self.BankAccount=self._to_bytes(BankAccount)
self.BankPassWord=self._to_bytes(BankPassWord)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.CurrencyID=self._to_bytes(CurrencyID)
self.TradeAmount=float(TradeAmount)
self.Digest=self._to_bytes(Digest)
self.LongCustomerName=self._to_bytes(LongCustomerName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.Reference=int(i_tuple[13])
self.RefrenceIssureType=self._to_bytes(i_tuple[14])
self.RefrenceIssure=self._to_bytes(i_tuple[15])
self.CustomerName=self._to_bytes(i_tuple[16])
self.IdCardType=self._to_bytes(i_tuple[17])
self.IdentifiedCardNo=self._to_bytes(i_tuple[18])
self.CustType=self._to_bytes(i_tuple[19])
self.BankAccount=self._to_bytes(i_tuple[20])
self.BankPassWord=self._to_bytes(i_tuple[21])
self.AccountID=self._to_bytes(i_tuple[22])
self.Password=self._to_bytes(i_tuple[23])
self.CurrencyID=self._to_bytes(i_tuple[24])
self.TradeAmount=float(i_tuple[25])
self.Digest=self._to_bytes(i_tuple[26])
self.LongCustomerName=self._to_bytes(i_tuple[27])
class RspQueryTradeResultBySerialField(Base):
"""查询指定流水号的交易结果响应"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
,('Reference',ctypes.c_int)# 流水号
,('RefrenceIssureType',ctypes.c_char)# 本流水号发布者的机构类型
,('RefrenceIssure',ctypes.c_char*36)# 本流水号发布者机构编码
,('OriginReturnCode',ctypes.c_char*7)# 原始返回代码
,('OriginDescrInfoForReturnCode',ctypes.c_char*129)# 原始返回码描述
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankPassWord',ctypes.c_char*41)# 银行密码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 期货密码
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('TradeAmount',ctypes.c_double)# 转帐金额
,('Digest',ctypes.c_char*36)# 摘要
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,ErrorID=0,ErrorMsg='',Reference=0,RefrenceIssureType='',RefrenceIssure='',OriginReturnCode='',OriginDescrInfoForReturnCode='',BankAccount='',BankPassWord='',AccountID='',Password='',CurrencyID='',TradeAmount=0.0,Digest=''):
super(RspQueryTradeResultBySerialField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
self.Reference=int(Reference)
self.RefrenceIssureType=self._to_bytes(RefrenceIssureType)
self.RefrenceIssure=self._to_bytes(RefrenceIssure)
self.OriginReturnCode=self._to_bytes(OriginReturnCode)
self.OriginDescrInfoForReturnCode=self._to_bytes(OriginDescrInfoForReturnCode)
self.BankAccount=self._to_bytes(BankAccount)
self.BankPassWord=self._to_bytes(BankPassWord)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.CurrencyID=self._to_bytes(CurrencyID)
self.TradeAmount=float(TradeAmount)
self.Digest=self._to_bytes(Digest)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.ErrorID=int(i_tuple[13])
self.ErrorMsg=self._to_bytes(i_tuple[14])
self.Reference=int(i_tuple[15])
self.RefrenceIssureType=self._to_bytes(i_tuple[16])
self.RefrenceIssure=self._to_bytes(i_tuple[17])
self.OriginReturnCode=self._to_bytes(i_tuple[18])
self.OriginDescrInfoForReturnCode=self._to_bytes(i_tuple[19])
self.BankAccount=self._to_bytes(i_tuple[20])
self.BankPassWord=self._to_bytes(i_tuple[21])
self.AccountID=self._to_bytes(i_tuple[22])
self.Password=self._to_bytes(i_tuple[23])
self.CurrencyID=self._to_bytes(i_tuple[24])
self.TradeAmount=float(i_tuple[25])
self.Digest=self._to_bytes(i_tuple[26])
class ReqDayEndFileReadyField(Base):
"""日终文件就绪请求"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('FileBusinessCode',ctypes.c_char)# 文件业务功能
,('Digest',ctypes.c_char*36)# 摘要
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,FileBusinessCode='',Digest=''):
super(ReqDayEndFileReadyField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.FileBusinessCode=self._to_bytes(FileBusinessCode)
self.Digest=self._to_bytes(Digest)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.FileBusinessCode=self._to_bytes(i_tuple[13])
self.Digest=self._to_bytes(i_tuple[14])
class ReturnResultField(Base):
"""返回结果"""
_fields_ = [
('ReturnCode',ctypes.c_char*7)# ///返回代码
,('DescrInfoForReturnCode',ctypes.c_char*129)# 返回码描述
]
def __init__(self,ReturnCode= '',DescrInfoForReturnCode=''):
super(ReturnResultField,self).__init__()
self.ReturnCode=self._to_bytes(ReturnCode)
self.DescrInfoForReturnCode=self._to_bytes(DescrInfoForReturnCode)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.ReturnCode=self._to_bytes(i_tuple[1])
self.DescrInfoForReturnCode=self._to_bytes(i_tuple[2])
class VerifyFuturePasswordField(Base):
"""验证期货资金密码"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 期货密码
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankPassWord',ctypes.c_char*41)# 银行密码
,('InstallID',ctypes.c_int)# 安装编号
,('TID',ctypes.c_int)# 交易ID
,('CurrencyID',ctypes.c_char*4)# 币种代码
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,AccountID='',Password='',BankAccount='',BankPassWord='',InstallID=0,TID=0,CurrencyID=''):
super(VerifyFuturePasswordField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.BankAccount=self._to_bytes(BankAccount)
self.BankPassWord=self._to_bytes(BankPassWord)
self.InstallID=int(InstallID)
self.TID=int(TID)
self.CurrencyID=self._to_bytes(CurrencyID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.AccountID=self._to_bytes(i_tuple[13])
self.Password=self._to_bytes(i_tuple[14])
self.BankAccount=self._to_bytes(i_tuple[15])
self.BankPassWord=self._to_bytes(i_tuple[16])
self.InstallID=int(i_tuple[17])
self.TID=int(i_tuple[18])
self.CurrencyID=self._to_bytes(i_tuple[19])
class VerifyCustInfoField(Base):
"""验证客户信息"""
_fields_ = [
('CustomerName',ctypes.c_char*51)# ///客户姓名
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('CustType',ctypes.c_char)# 客户类型
,('LongCustomerName',ctypes.c_char*161)# 长客户姓名
]
def __init__(self,CustomerName= '',IdCardType='',IdentifiedCardNo='',CustType='',LongCustomerName=''):
super(VerifyCustInfoField,self).__init__()
self.CustomerName=self._to_bytes(CustomerName)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.CustType=self._to_bytes(CustType)
self.LongCustomerName=self._to_bytes(LongCustomerName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.CustomerName=self._to_bytes(i_tuple[1])
self.IdCardType=self._to_bytes(i_tuple[2])
self.IdentifiedCardNo=self._to_bytes(i_tuple[3])
self.CustType=self._to_bytes(i_tuple[4])
self.LongCustomerName=self._to_bytes(i_tuple[5])
class VerifyFuturePasswordAndCustInfoField(Base):
"""验证期货资金密码和客户信息"""
_fields_ = [
('CustomerName',ctypes.c_char*51)# ///客户姓名
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('CustType',ctypes.c_char)# 客户类型
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 期货密码
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('LongCustomerName',ctypes.c_char*161)# 长客户姓名
]
def __init__(self,CustomerName= '',IdCardType='',IdentifiedCardNo='',CustType='',AccountID='',Password='',CurrencyID='',LongCustomerName=''):
super(VerifyFuturePasswordAndCustInfoField,self).__init__()
self.CustomerName=self._to_bytes(CustomerName)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.CustType=self._to_bytes(CustType)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.CurrencyID=self._to_bytes(CurrencyID)
self.LongCustomerName=self._to_bytes(LongCustomerName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.CustomerName=self._to_bytes(i_tuple[1])
self.IdCardType=self._to_bytes(i_tuple[2])
self.IdentifiedCardNo=self._to_bytes(i_tuple[3])
self.CustType=self._to_bytes(i_tuple[4])
self.AccountID=self._to_bytes(i_tuple[5])
self.Password=self._to_bytes(i_tuple[6])
self.CurrencyID=self._to_bytes(i_tuple[7])
self.LongCustomerName=self._to_bytes(i_tuple[8])
class DepositResultInformField(Base):
"""验证期货资金密码和客户信息"""
_fields_ = [
('DepositSeqNo',ctypes.c_char*15)# ///出入金流水号,该流水号为银期报盘返回的流水号
,('BrokerID',ctypes.c_char*11)# 经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('Deposit',ctypes.c_double)# 入金金额
,('RequestID',ctypes.c_int)# 请求编号
,('ReturnCode',ctypes.c_char*7)# 返回代码
,('DescrInfoForReturnCode',ctypes.c_char*129)# 返回码描述
]
def __init__(self,DepositSeqNo= '',BrokerID='',InvestorID='',Deposit=0.0,RequestID=0,ReturnCode='',DescrInfoForReturnCode=''):
super(DepositResultInformField,self).__init__()
self.DepositSeqNo=self._to_bytes(DepositSeqNo)
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
self.Deposit=float(Deposit)
self.RequestID=int(RequestID)
self.ReturnCode=self._to_bytes(ReturnCode)
self.DescrInfoForReturnCode=self._to_bytes(DescrInfoForReturnCode)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.DepositSeqNo=self._to_bytes(i_tuple[1])
self.BrokerID=self._to_bytes(i_tuple[2])
self.InvestorID=self._to_bytes(i_tuple[3])
self.Deposit=float(i_tuple[4])
self.RequestID=int(i_tuple[5])
self.ReturnCode=self._to_bytes(i_tuple[6])
self.DescrInfoForReturnCode=self._to_bytes(i_tuple[7])
class ReqSyncKeyField(Base):
"""交易核心向银期报盘发出密钥同步请求"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('InstallID',ctypes.c_int)# 安装编号
,('UserID',ctypes.c_char*16)# 用户标识
,('Message',ctypes.c_char*129)# 交易核心给银期报盘的消息
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('OperNo',ctypes.c_char*17)# 交易柜员
,('RequestID',ctypes.c_int)# 请求编号
,('TID',ctypes.c_int)# 交易ID
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,InstallID=0,UserID='',Message='',DeviceID='',BrokerIDByBank='',OperNo='',RequestID=0,TID=0):
super(ReqSyncKeyField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.InstallID=int(InstallID)
self.UserID=self._to_bytes(UserID)
self.Message=self._to_bytes(Message)
self.DeviceID=self._to_bytes(DeviceID)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.OperNo=self._to_bytes(OperNo)
self.RequestID=int(RequestID)
self.TID=int(TID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.InstallID=int(i_tuple[13])
self.UserID=self._to_bytes(i_tuple[14])
self.Message=self._to_bytes(i_tuple[15])
self.DeviceID=self._to_bytes(i_tuple[16])
self.BrokerIDByBank=self._to_bytes(i_tuple[17])
self.OperNo=self._to_bytes(i_tuple[18])
self.RequestID=int(i_tuple[19])
self.TID=int(i_tuple[20])
class RspSyncKeyField(Base):
"""交易核心向银期报盘发出密钥同步响应"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('InstallID',ctypes.c_int)# 安装编号
,('UserID',ctypes.c_char*16)# 用户标识
,('Message',ctypes.c_char*129)# 交易核心给银期报盘的消息
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('OperNo',ctypes.c_char*17)# 交易柜员
,('RequestID',ctypes.c_int)# 请求编号
,('TID',ctypes.c_int)# 交易ID
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,InstallID=0,UserID='',Message='',DeviceID='',BrokerIDByBank='',OperNo='',RequestID=0,TID=0,ErrorID=0,ErrorMsg=''):
super(RspSyncKeyField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.InstallID=int(InstallID)
self.UserID=self._to_bytes(UserID)
self.Message=self._to_bytes(Message)
self.DeviceID=self._to_bytes(DeviceID)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.OperNo=self._to_bytes(OperNo)
self.RequestID=int(RequestID)
self.TID=int(TID)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.InstallID=int(i_tuple[13])
self.UserID=self._to_bytes(i_tuple[14])
self.Message=self._to_bytes(i_tuple[15])
self.DeviceID=self._to_bytes(i_tuple[16])
self.BrokerIDByBank=self._to_bytes(i_tuple[17])
self.OperNo=self._to_bytes(i_tuple[18])
self.RequestID=int(i_tuple[19])
self.TID=int(i_tuple[20])
self.ErrorID=int(i_tuple[21])
self.ErrorMsg=self._to_bytes(i_tuple[22])
class NotifyQueryAccountField(Base):
"""查询账户信息通知"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('CustomerName',ctypes.c_char*51)# 客户姓名
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('CustType',ctypes.c_char)# 客户类型
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankPassWord',ctypes.c_char*41)# 银行密码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 期货密码
,('FutureSerial',ctypes.c_int)# 期货公司流水号
,('InstallID',ctypes.c_int)# 安装编号
,('UserID',ctypes.c_char*16)# 用户标识
,('VerifyCertNoFlag',ctypes.c_char)# 验证客户证件号码标志
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('Digest',ctypes.c_char*36)# 摘要
,('BankAccType',ctypes.c_char)# 银行帐号类型
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BankSecuAccType',ctypes.c_char)# 期货单位帐号类型
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('BankSecuAcc',ctypes.c_char*41)# 期货单位帐号
,('BankPwdFlag',ctypes.c_char)# 银行密码标志
,('SecuPwdFlag',ctypes.c_char)# 期货资金密码核对标志
,('OperNo',ctypes.c_char*17)# 交易柜员
,('RequestID',ctypes.c_int)# 请求编号
,('TID',ctypes.c_int)# 交易ID
,('BankUseAmount',ctypes.c_double)# 银行可用金额
,('BankFetchAmount',ctypes.c_double)# 银行可取金额
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
,('LongCustomerName',ctypes.c_char*161)# 长客户姓名
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,CustomerName='',IdCardType='',IdentifiedCardNo='',CustType='',BankAccount='',BankPassWord='',AccountID='',Password='',FutureSerial=0,InstallID=0,UserID='',VerifyCertNoFlag='',CurrencyID='',Digest='',BankAccType='',DeviceID='',BankSecuAccType='',BrokerIDByBank='',BankSecuAcc='',BankPwdFlag='',SecuPwdFlag='',OperNo='',RequestID=0,TID=0,BankUseAmount=0.0,BankFetchAmount=0.0,ErrorID=0,ErrorMsg='',LongCustomerName=''):
super(NotifyQueryAccountField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.CustomerName=self._to_bytes(CustomerName)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.CustType=self._to_bytes(CustType)
self.BankAccount=self._to_bytes(BankAccount)
self.BankPassWord=self._to_bytes(BankPassWord)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.FutureSerial=int(FutureSerial)
self.InstallID=int(InstallID)
self.UserID=self._to_bytes(UserID)
self.VerifyCertNoFlag=self._to_bytes(VerifyCertNoFlag)
self.CurrencyID=self._to_bytes(CurrencyID)
self.Digest=self._to_bytes(Digest)
self.BankAccType=self._to_bytes(BankAccType)
self.DeviceID=self._to_bytes(DeviceID)
self.BankSecuAccType=self._to_bytes(BankSecuAccType)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.BankSecuAcc=self._to_bytes(BankSecuAcc)
self.BankPwdFlag=self._to_bytes(BankPwdFlag)
self.SecuPwdFlag=self._to_bytes(SecuPwdFlag)
self.OperNo=self._to_bytes(OperNo)
self.RequestID=int(RequestID)
self.TID=int(TID)
self.BankUseAmount=float(BankUseAmount)
self.BankFetchAmount=float(BankFetchAmount)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
self.LongCustomerName=self._to_bytes(LongCustomerName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.CustomerName=self._to_bytes(i_tuple[13])
self.IdCardType=self._to_bytes(i_tuple[14])
self.IdentifiedCardNo=self._to_bytes(i_tuple[15])
self.CustType=self._to_bytes(i_tuple[16])
self.BankAccount=self._to_bytes(i_tuple[17])
self.BankPassWord=self._to_bytes(i_tuple[18])
self.AccountID=self._to_bytes(i_tuple[19])
self.Password=self._to_bytes(i_tuple[20])
self.FutureSerial=int(i_tuple[21])
self.InstallID=int(i_tuple[22])
self.UserID=self._to_bytes(i_tuple[23])
self.VerifyCertNoFlag=self._to_bytes(i_tuple[24])
self.CurrencyID=self._to_bytes(i_tuple[25])
self.Digest=self._to_bytes(i_tuple[26])
self.BankAccType=self._to_bytes(i_tuple[27])
self.DeviceID=self._to_bytes(i_tuple[28])
self.BankSecuAccType=self._to_bytes(i_tuple[29])
self.BrokerIDByBank=self._to_bytes(i_tuple[30])
self.BankSecuAcc=self._to_bytes(i_tuple[31])
self.BankPwdFlag=self._to_bytes(i_tuple[32])
self.SecuPwdFlag=self._to_bytes(i_tuple[33])
self.OperNo=self._to_bytes(i_tuple[34])
self.RequestID=int(i_tuple[35])
self.TID=int(i_tuple[36])
self.BankUseAmount=float(i_tuple[37])
self.BankFetchAmount=float(i_tuple[38])
self.ErrorID=int(i_tuple[39])
self.ErrorMsg=self._to_bytes(i_tuple[40])
self.LongCustomerName=self._to_bytes(i_tuple[41])
class TransferSerialField(Base):
"""银期转账交易流水表"""
_fields_ = [
('PlateSerial',ctypes.c_int)# ///平台流水号
,('TradeDate',ctypes.c_char*9)# 交易发起方日期
,('TradingDay',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('TradeCode',ctypes.c_char*7)# 交易代码
,('SessionID',ctypes.c_int)# 会话编号
,('BankID',ctypes.c_char*4)# 银行编码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构编码
,('BankAccType',ctypes.c_char)# 银行帐号类型
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('BrokerID',ctypes.c_char*11)# 期货公司编码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('FutureAccType',ctypes.c_char)# 期货公司帐号类型
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('InvestorID',ctypes.c_char*13)# 投资者代码
,('FutureSerial',ctypes.c_int)# 期货公司流水号
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('TradeAmount',ctypes.c_double)# 交易金额
,('CustFee',ctypes.c_double)# 应收客户费用
,('BrokerFee',ctypes.c_double)# 应收期货公司费用
,('AvailabilityFlag',ctypes.c_char)# 有效标志
,('OperatorCode',ctypes.c_char*17)# 操作员
,('BankNewAccount',ctypes.c_char*41)# 新银行帐号
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
]
def __init__(self,PlateSerial= 0,TradeDate='',TradingDay='',TradeTime='',TradeCode='',SessionID=0,BankID='',BankBranchID='',BankAccType='',BankAccount='',BankSerial='',BrokerID='',BrokerBranchID='',FutureAccType='',AccountID='',InvestorID='',FutureSerial=0,IdCardType='',IdentifiedCardNo='',CurrencyID='',TradeAmount=0.0,CustFee=0.0,BrokerFee=0.0,AvailabilityFlag='',OperatorCode='',BankNewAccount='',ErrorID=0,ErrorMsg=''):
super(TransferSerialField,self).__init__()
self.PlateSerial=int(PlateSerial)
self.TradeDate=self._to_bytes(TradeDate)
self.TradingDay=self._to_bytes(TradingDay)
self.TradeTime=self._to_bytes(TradeTime)
self.TradeCode=self._to_bytes(TradeCode)
self.SessionID=int(SessionID)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BankAccType=self._to_bytes(BankAccType)
self.BankAccount=self._to_bytes(BankAccount)
self.BankSerial=self._to_bytes(BankSerial)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.FutureAccType=self._to_bytes(FutureAccType)
self.AccountID=self._to_bytes(AccountID)
self.InvestorID=self._to_bytes(InvestorID)
self.FutureSerial=int(FutureSerial)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.CurrencyID=self._to_bytes(CurrencyID)
self.TradeAmount=float(TradeAmount)
self.CustFee=float(CustFee)
self.BrokerFee=float(BrokerFee)
self.AvailabilityFlag=self._to_bytes(AvailabilityFlag)
self.OperatorCode=self._to_bytes(OperatorCode)
self.BankNewAccount=self._to_bytes(BankNewAccount)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.PlateSerial=int(i_tuple[1])
self.TradeDate=self._to_bytes(i_tuple[2])
self.TradingDay=self._to_bytes(i_tuple[3])
self.TradeTime=self._to_bytes(i_tuple[4])
self.TradeCode=self._to_bytes(i_tuple[5])
self.SessionID=int(i_tuple[6])
self.BankID=self._to_bytes(i_tuple[7])
self.BankBranchID=self._to_bytes(i_tuple[8])
self.BankAccType=self._to_bytes(i_tuple[9])
self.BankAccount=self._to_bytes(i_tuple[10])
self.BankSerial=self._to_bytes(i_tuple[11])
self.BrokerID=self._to_bytes(i_tuple[12])
self.BrokerBranchID=self._to_bytes(i_tuple[13])
self.FutureAccType=self._to_bytes(i_tuple[14])
self.AccountID=self._to_bytes(i_tuple[15])
self.InvestorID=self._to_bytes(i_tuple[16])
self.FutureSerial=int(i_tuple[17])
self.IdCardType=self._to_bytes(i_tuple[18])
self.IdentifiedCardNo=self._to_bytes(i_tuple[19])
self.CurrencyID=self._to_bytes(i_tuple[20])
self.TradeAmount=float(i_tuple[21])
self.CustFee=float(i_tuple[22])
self.BrokerFee=float(i_tuple[23])
self.AvailabilityFlag=self._to_bytes(i_tuple[24])
self.OperatorCode=self._to_bytes(i_tuple[25])
self.BankNewAccount=self._to_bytes(i_tuple[26])
self.ErrorID=int(i_tuple[27])
self.ErrorMsg=self._to_bytes(i_tuple[28])
class QryTransferSerialField(Base):
"""请求查询转帐流水"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('BankID',ctypes.c_char*4)# 银行编码
,('CurrencyID',ctypes.c_char*4)# 币种代码
]
def __init__(self,BrokerID= '',AccountID='',BankID='',CurrencyID=''):
super(QryTransferSerialField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.AccountID=self._to_bytes(AccountID)
self.BankID=self._to_bytes(BankID)
self.CurrencyID=self._to_bytes(CurrencyID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.AccountID=self._to_bytes(i_tuple[2])
self.BankID=self._to_bytes(i_tuple[3])
self.CurrencyID=self._to_bytes(i_tuple[4])
class NotifyFutureSignInField(Base):
"""期商签到通知"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('InstallID',ctypes.c_int)# 安装编号
,('UserID',ctypes.c_char*16)# 用户标识
,('Digest',ctypes.c_char*36)# 摘要
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('OperNo',ctypes.c_char*17)# 交易柜员
,('RequestID',ctypes.c_int)# 请求编号
,('TID',ctypes.c_int)# 交易ID
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
,('PinKey',ctypes.c_char*129)# PIN密钥
,('MacKey',ctypes.c_char*129)# MAC密钥
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,InstallID=0,UserID='',Digest='',CurrencyID='',DeviceID='',BrokerIDByBank='',OperNo='',RequestID=0,TID=0,ErrorID=0,ErrorMsg='',PinKey='',MacKey=''):
super(NotifyFutureSignInField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.InstallID=int(InstallID)
self.UserID=self._to_bytes(UserID)
self.Digest=self._to_bytes(Digest)
self.CurrencyID=self._to_bytes(CurrencyID)
self.DeviceID=self._to_bytes(DeviceID)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.OperNo=self._to_bytes(OperNo)
self.RequestID=int(RequestID)
self.TID=int(TID)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
self.PinKey=self._to_bytes(PinKey)
self.MacKey=self._to_bytes(MacKey)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.InstallID=int(i_tuple[13])
self.UserID=self._to_bytes(i_tuple[14])
self.Digest=self._to_bytes(i_tuple[15])
self.CurrencyID=self._to_bytes(i_tuple[16])
self.DeviceID=self._to_bytes(i_tuple[17])
self.BrokerIDByBank=self._to_bytes(i_tuple[18])
self.OperNo=self._to_bytes(i_tuple[19])
self.RequestID=int(i_tuple[20])
self.TID=int(i_tuple[21])
self.ErrorID=int(i_tuple[22])
self.ErrorMsg=self._to_bytes(i_tuple[23])
self.PinKey=self._to_bytes(i_tuple[24])
self.MacKey=self._to_bytes(i_tuple[25])
class NotifyFutureSignOutField(Base):
"""期商签退通知"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('InstallID',ctypes.c_int)# 安装编号
,('UserID',ctypes.c_char*16)# 用户标识
,('Digest',ctypes.c_char*36)# 摘要
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('OperNo',ctypes.c_char*17)# 交易柜员
,('RequestID',ctypes.c_int)# 请求编号
,('TID',ctypes.c_int)# 交易ID
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,InstallID=0,UserID='',Digest='',CurrencyID='',DeviceID='',BrokerIDByBank='',OperNo='',RequestID=0,TID=0,ErrorID=0,ErrorMsg=''):
super(NotifyFutureSignOutField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.InstallID=int(InstallID)
self.UserID=self._to_bytes(UserID)
self.Digest=self._to_bytes(Digest)
self.CurrencyID=self._to_bytes(CurrencyID)
self.DeviceID=self._to_bytes(DeviceID)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.OperNo=self._to_bytes(OperNo)
self.RequestID=int(RequestID)
self.TID=int(TID)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.InstallID=int(i_tuple[13])
self.UserID=self._to_bytes(i_tuple[14])
self.Digest=self._to_bytes(i_tuple[15])
self.CurrencyID=self._to_bytes(i_tuple[16])
self.DeviceID=self._to_bytes(i_tuple[17])
self.BrokerIDByBank=self._to_bytes(i_tuple[18])
self.OperNo=self._to_bytes(i_tuple[19])
self.RequestID=int(i_tuple[20])
self.TID=int(i_tuple[21])
self.ErrorID=int(i_tuple[22])
self.ErrorMsg=self._to_bytes(i_tuple[23])
class NotifySyncKeyField(Base):
"""交易核心向银期报盘发出密钥同步处理结果的通知"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('InstallID',ctypes.c_int)# 安装编号
,('UserID',ctypes.c_char*16)# 用户标识
,('Message',ctypes.c_char*129)# 交易核心给银期报盘的消息
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('OperNo',ctypes.c_char*17)# 交易柜员
,('RequestID',ctypes.c_int)# 请求编号
,('TID',ctypes.c_int)# 交易ID
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,InstallID=0,UserID='',Message='',DeviceID='',BrokerIDByBank='',OperNo='',RequestID=0,TID=0,ErrorID=0,ErrorMsg=''):
super(NotifySyncKeyField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.InstallID=int(InstallID)
self.UserID=self._to_bytes(UserID)
self.Message=self._to_bytes(Message)
self.DeviceID=self._to_bytes(DeviceID)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.OperNo=self._to_bytes(OperNo)
self.RequestID=int(RequestID)
self.TID=int(TID)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.InstallID=int(i_tuple[13])
self.UserID=self._to_bytes(i_tuple[14])
self.Message=self._to_bytes(i_tuple[15])
self.DeviceID=self._to_bytes(i_tuple[16])
self.BrokerIDByBank=self._to_bytes(i_tuple[17])
self.OperNo=self._to_bytes(i_tuple[18])
self.RequestID=int(i_tuple[19])
self.TID=int(i_tuple[20])
self.ErrorID=int(i_tuple[21])
self.ErrorMsg=self._to_bytes(i_tuple[22])
class QryAccountregisterField(Base):
"""请求查询银期签约关系"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('BankID',ctypes.c_char*4)# 银行编码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构编码
,('CurrencyID',ctypes.c_char*4)# 币种代码
]
def __init__(self,BrokerID= '',AccountID='',BankID='',BankBranchID='',CurrencyID=''):
super(QryAccountregisterField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.AccountID=self._to_bytes(AccountID)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.CurrencyID=self._to_bytes(CurrencyID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.AccountID=self._to_bytes(i_tuple[2])
self.BankID=self._to_bytes(i_tuple[3])
self.BankBranchID=self._to_bytes(i_tuple[4])
self.CurrencyID=self._to_bytes(i_tuple[5])
class AccountregisterField(Base):
"""客户开销户信息表"""
_fields_ = [
('TradeDay',ctypes.c_char*9)# ///交易日期
,('BankID',ctypes.c_char*4)# 银行编码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构编码
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BrokerID',ctypes.c_char*11)# 期货公司编码
,('BrokerBranchID',ctypes.c_char*31)# 期货公司分支机构编码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('CustomerName',ctypes.c_char*51)# 客户姓名
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('OpenOrDestroy',ctypes.c_char)# 开销户类别
,('RegDate',ctypes.c_char*9)# 签约日期
,('OutDate',ctypes.c_char*9)# 解约日期
,('TID',ctypes.c_int)# 交易ID
,('CustType',ctypes.c_char)# 客户类型
,('BankAccType',ctypes.c_char)# 银行帐号类型
,('LongCustomerName',ctypes.c_char*161)# 长客户姓名
]
def __init__(self,TradeDay= '',BankID='',BankBranchID='',BankAccount='',BrokerID='',BrokerBranchID='',AccountID='',IdCardType='',IdentifiedCardNo='',CustomerName='',CurrencyID='',OpenOrDestroy='',RegDate='',OutDate='',TID=0,CustType='',BankAccType='',LongCustomerName=''):
super(AccountregisterField,self).__init__()
self.TradeDay=self._to_bytes(TradeDay)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BankAccount=self._to_bytes(BankAccount)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.AccountID=self._to_bytes(AccountID)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.CustomerName=self._to_bytes(CustomerName)
self.CurrencyID=self._to_bytes(CurrencyID)
self.OpenOrDestroy=self._to_bytes(OpenOrDestroy)
self.RegDate=self._to_bytes(RegDate)
self.OutDate=self._to_bytes(OutDate)
self.TID=int(TID)
self.CustType=self._to_bytes(CustType)
self.BankAccType=self._to_bytes(BankAccType)
self.LongCustomerName=self._to_bytes(LongCustomerName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeDay=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BankAccount=self._to_bytes(i_tuple[4])
self.BrokerID=self._to_bytes(i_tuple[5])
self.BrokerBranchID=self._to_bytes(i_tuple[6])
self.AccountID=self._to_bytes(i_tuple[7])
self.IdCardType=self._to_bytes(i_tuple[8])
self.IdentifiedCardNo=self._to_bytes(i_tuple[9])
self.CustomerName=self._to_bytes(i_tuple[10])
self.CurrencyID=self._to_bytes(i_tuple[11])
self.OpenOrDestroy=self._to_bytes(i_tuple[12])
self.RegDate=self._to_bytes(i_tuple[13])
self.OutDate=self._to_bytes(i_tuple[14])
self.TID=int(i_tuple[15])
self.CustType=self._to_bytes(i_tuple[16])
self.BankAccType=self._to_bytes(i_tuple[17])
self.LongCustomerName=self._to_bytes(i_tuple[18])
class OpenAccountField(Base):
"""银期开户信息"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('CustomerName',ctypes.c_char*51)# 客户姓名
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('Gender',ctypes.c_char)# 性别
,('CountryCode',ctypes.c_char*21)# 国家代码
,('CustType',ctypes.c_char)# 客户类型
,('Address',ctypes.c_char*101)# 地址
,('ZipCode',ctypes.c_char*7)# 邮编
,('Telephone',ctypes.c_char*41)# 电话号码
,('MobilePhone',ctypes.c_char*21)# 手机
,('Fax',ctypes.c_char*41)# 传真
,('EMail',ctypes.c_char*41)# 电子邮件
,('MoneyAccountStatus',ctypes.c_char)# 资金账户状态
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankPassWord',ctypes.c_char*41)# 银行密码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 期货密码
,('InstallID',ctypes.c_int)# 安装编号
,('VerifyCertNoFlag',ctypes.c_char)# 验证客户证件号码标志
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('CashExchangeCode',ctypes.c_char)# 汇钞标志
,('Digest',ctypes.c_char*36)# 摘要
,('BankAccType',ctypes.c_char)# 银行帐号类型
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BankSecuAccType',ctypes.c_char)# 期货单位帐号类型
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('BankSecuAcc',ctypes.c_char*41)# 期货单位帐号
,('BankPwdFlag',ctypes.c_char)# 银行密码标志
,('SecuPwdFlag',ctypes.c_char)# 期货资金密码核对标志
,('OperNo',ctypes.c_char*17)# 交易柜员
,('TID',ctypes.c_int)# 交易ID
,('UserID',ctypes.c_char*16)# 用户标识
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
,('LongCustomerName',ctypes.c_char*161)# 长客户姓名
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,CustomerName='',IdCardType='',IdentifiedCardNo='',Gender='',CountryCode='',CustType='',Address='',ZipCode='',Telephone='',MobilePhone='',Fax='',EMail='',MoneyAccountStatus='',BankAccount='',BankPassWord='',AccountID='',Password='',InstallID=0,VerifyCertNoFlag='',CurrencyID='',CashExchangeCode='',Digest='',BankAccType='',DeviceID='',BankSecuAccType='',BrokerIDByBank='',BankSecuAcc='',BankPwdFlag='',SecuPwdFlag='',OperNo='',TID=0,UserID='',ErrorID=0,ErrorMsg='',LongCustomerName=''):
super(OpenAccountField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.CustomerName=self._to_bytes(CustomerName)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.Gender=self._to_bytes(Gender)
self.CountryCode=self._to_bytes(CountryCode)
self.CustType=self._to_bytes(CustType)
self.Address=self._to_bytes(Address)
self.ZipCode=self._to_bytes(ZipCode)
self.Telephone=self._to_bytes(Telephone)
self.MobilePhone=self._to_bytes(MobilePhone)
self.Fax=self._to_bytes(Fax)
self.EMail=self._to_bytes(EMail)
self.MoneyAccountStatus=self._to_bytes(MoneyAccountStatus)
self.BankAccount=self._to_bytes(BankAccount)
self.BankPassWord=self._to_bytes(BankPassWord)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.InstallID=int(InstallID)
self.VerifyCertNoFlag=self._to_bytes(VerifyCertNoFlag)
self.CurrencyID=self._to_bytes(CurrencyID)
self.CashExchangeCode=self._to_bytes(CashExchangeCode)
self.Digest=self._to_bytes(Digest)
self.BankAccType=self._to_bytes(BankAccType)
self.DeviceID=self._to_bytes(DeviceID)
self.BankSecuAccType=self._to_bytes(BankSecuAccType)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.BankSecuAcc=self._to_bytes(BankSecuAcc)
self.BankPwdFlag=self._to_bytes(BankPwdFlag)
self.SecuPwdFlag=self._to_bytes(SecuPwdFlag)
self.OperNo=self._to_bytes(OperNo)
self.TID=int(TID)
self.UserID=self._to_bytes(UserID)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
self.LongCustomerName=self._to_bytes(LongCustomerName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.CustomerName=self._to_bytes(i_tuple[13])
self.IdCardType=self._to_bytes(i_tuple[14])
self.IdentifiedCardNo=self._to_bytes(i_tuple[15])
self.Gender=self._to_bytes(i_tuple[16])
self.CountryCode=self._to_bytes(i_tuple[17])
self.CustType=self._to_bytes(i_tuple[18])
self.Address=self._to_bytes(i_tuple[19])
self.ZipCode=self._to_bytes(i_tuple[20])
self.Telephone=self._to_bytes(i_tuple[21])
self.MobilePhone=self._to_bytes(i_tuple[22])
self.Fax=self._to_bytes(i_tuple[23])
self.EMail=self._to_bytes(i_tuple[24])
self.MoneyAccountStatus=self._to_bytes(i_tuple[25])
self.BankAccount=self._to_bytes(i_tuple[26])
self.BankPassWord=self._to_bytes(i_tuple[27])
self.AccountID=self._to_bytes(i_tuple[28])
self.Password=self._to_bytes(i_tuple[29])
self.InstallID=int(i_tuple[30])
self.VerifyCertNoFlag=self._to_bytes(i_tuple[31])
self.CurrencyID=self._to_bytes(i_tuple[32])
self.CashExchangeCode=self._to_bytes(i_tuple[33])
self.Digest=self._to_bytes(i_tuple[34])
self.BankAccType=self._to_bytes(i_tuple[35])
self.DeviceID=self._to_bytes(i_tuple[36])
self.BankSecuAccType=self._to_bytes(i_tuple[37])
self.BrokerIDByBank=self._to_bytes(i_tuple[38])
self.BankSecuAcc=self._to_bytes(i_tuple[39])
self.BankPwdFlag=self._to_bytes(i_tuple[40])
self.SecuPwdFlag=self._to_bytes(i_tuple[41])
self.OperNo=self._to_bytes(i_tuple[42])
self.TID=int(i_tuple[43])
self.UserID=self._to_bytes(i_tuple[44])
self.ErrorID=int(i_tuple[45])
self.ErrorMsg=self._to_bytes(i_tuple[46])
self.LongCustomerName=self._to_bytes(i_tuple[47])
class CancelAccountField(Base):
"""银期销户信息"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('CustomerName',ctypes.c_char*51)# 客户姓名
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('Gender',ctypes.c_char)# 性别
,('CountryCode',ctypes.c_char*21)# 国家代码
,('CustType',ctypes.c_char)# 客户类型
,('Address',ctypes.c_char*101)# 地址
,('ZipCode',ctypes.c_char*7)# 邮编
,('Telephone',ctypes.c_char*41)# 电话号码
,('MobilePhone',ctypes.c_char*21)# 手机
,('Fax',ctypes.c_char*41)# 传真
,('EMail',ctypes.c_char*41)# 电子邮件
,('MoneyAccountStatus',ctypes.c_char)# 资金账户状态
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankPassWord',ctypes.c_char*41)# 银行密码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 期货密码
,('InstallID',ctypes.c_int)# 安装编号
,('VerifyCertNoFlag',ctypes.c_char)# 验证客户证件号码标志
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('CashExchangeCode',ctypes.c_char)# 汇钞标志
,('Digest',ctypes.c_char*36)# 摘要
,('BankAccType',ctypes.c_char)# 银行帐号类型
,('DeviceID',ctypes.c_char*3)# 渠道标志
,('BankSecuAccType',ctypes.c_char)# 期货单位帐号类型
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('BankSecuAcc',ctypes.c_char*41)# 期货单位帐号
,('BankPwdFlag',ctypes.c_char)# 银行密码标志
,('SecuPwdFlag',ctypes.c_char)# 期货资金密码核对标志
,('OperNo',ctypes.c_char*17)# 交易柜员
,('TID',ctypes.c_int)# 交易ID
,('UserID',ctypes.c_char*16)# 用户标识
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
,('LongCustomerName',ctypes.c_char*161)# 长客户姓名
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,CustomerName='',IdCardType='',IdentifiedCardNo='',Gender='',CountryCode='',CustType='',Address='',ZipCode='',Telephone='',MobilePhone='',Fax='',EMail='',MoneyAccountStatus='',BankAccount='',BankPassWord='',AccountID='',Password='',InstallID=0,VerifyCertNoFlag='',CurrencyID='',CashExchangeCode='',Digest='',BankAccType='',DeviceID='',BankSecuAccType='',BrokerIDByBank='',BankSecuAcc='',BankPwdFlag='',SecuPwdFlag='',OperNo='',TID=0,UserID='',ErrorID=0,ErrorMsg='',LongCustomerName=''):
super(CancelAccountField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.CustomerName=self._to_bytes(CustomerName)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.Gender=self._to_bytes(Gender)
self.CountryCode=self._to_bytes(CountryCode)
self.CustType=self._to_bytes(CustType)
self.Address=self._to_bytes(Address)
self.ZipCode=self._to_bytes(ZipCode)
self.Telephone=self._to_bytes(Telephone)
self.MobilePhone=self._to_bytes(MobilePhone)
self.Fax=self._to_bytes(Fax)
self.EMail=self._to_bytes(EMail)
self.MoneyAccountStatus=self._to_bytes(MoneyAccountStatus)
self.BankAccount=self._to_bytes(BankAccount)
self.BankPassWord=self._to_bytes(BankPassWord)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.InstallID=int(InstallID)
self.VerifyCertNoFlag=self._to_bytes(VerifyCertNoFlag)
self.CurrencyID=self._to_bytes(CurrencyID)
self.CashExchangeCode=self._to_bytes(CashExchangeCode)
self.Digest=self._to_bytes(Digest)
self.BankAccType=self._to_bytes(BankAccType)
self.DeviceID=self._to_bytes(DeviceID)
self.BankSecuAccType=self._to_bytes(BankSecuAccType)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.BankSecuAcc=self._to_bytes(BankSecuAcc)
self.BankPwdFlag=self._to_bytes(BankPwdFlag)
self.SecuPwdFlag=self._to_bytes(SecuPwdFlag)
self.OperNo=self._to_bytes(OperNo)
self.TID=int(TID)
self.UserID=self._to_bytes(UserID)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
self.LongCustomerName=self._to_bytes(LongCustomerName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.CustomerName=self._to_bytes(i_tuple[13])
self.IdCardType=self._to_bytes(i_tuple[14])
self.IdentifiedCardNo=self._to_bytes(i_tuple[15])
self.Gender=self._to_bytes(i_tuple[16])
self.CountryCode=self._to_bytes(i_tuple[17])
self.CustType=self._to_bytes(i_tuple[18])
self.Address=self._to_bytes(i_tuple[19])
self.ZipCode=self._to_bytes(i_tuple[20])
self.Telephone=self._to_bytes(i_tuple[21])
self.MobilePhone=self._to_bytes(i_tuple[22])
self.Fax=self._to_bytes(i_tuple[23])
self.EMail=self._to_bytes(i_tuple[24])
self.MoneyAccountStatus=self._to_bytes(i_tuple[25])
self.BankAccount=self._to_bytes(i_tuple[26])
self.BankPassWord=self._to_bytes(i_tuple[27])
self.AccountID=self._to_bytes(i_tuple[28])
self.Password=self._to_bytes(i_tuple[29])
self.InstallID=int(i_tuple[30])
self.VerifyCertNoFlag=self._to_bytes(i_tuple[31])
self.CurrencyID=self._to_bytes(i_tuple[32])
self.CashExchangeCode=self._to_bytes(i_tuple[33])
self.Digest=self._to_bytes(i_tuple[34])
self.BankAccType=self._to_bytes(i_tuple[35])
self.DeviceID=self._to_bytes(i_tuple[36])
self.BankSecuAccType=self._to_bytes(i_tuple[37])
self.BrokerIDByBank=self._to_bytes(i_tuple[38])
self.BankSecuAcc=self._to_bytes(i_tuple[39])
self.BankPwdFlag=self._to_bytes(i_tuple[40])
self.SecuPwdFlag=self._to_bytes(i_tuple[41])
self.OperNo=self._to_bytes(i_tuple[42])
self.TID=int(i_tuple[43])
self.UserID=self._to_bytes(i_tuple[44])
self.ErrorID=int(i_tuple[45])
self.ErrorMsg=self._to_bytes(i_tuple[46])
self.LongCustomerName=self._to_bytes(i_tuple[47])
class ChangeAccountField(Base):
"""银期变更银行账号信息"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('CustomerName',ctypes.c_char*51)# 客户姓名
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('Gender',ctypes.c_char)# 性别
,('CountryCode',ctypes.c_char*21)# 国家代码
,('CustType',ctypes.c_char)# 客户类型
,('Address',ctypes.c_char*101)# 地址
,('ZipCode',ctypes.c_char*7)# 邮编
,('Telephone',ctypes.c_char*41)# 电话号码
,('MobilePhone',ctypes.c_char*21)# 手机
,('Fax',ctypes.c_char*41)# 传真
,('EMail',ctypes.c_char*41)# 电子邮件
,('MoneyAccountStatus',ctypes.c_char)# 资金账户状态
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankPassWord',ctypes.c_char*41)# 银行密码
,('NewBankAccount',ctypes.c_char*41)# 新银行帐号
,('NewBankPassWord',ctypes.c_char*41)# 新银行密码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 期货密码
,('BankAccType',ctypes.c_char)# 银行帐号类型
,('InstallID',ctypes.c_int)# 安装编号
,('VerifyCertNoFlag',ctypes.c_char)# 验证客户证件号码标志
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('BankPwdFlag',ctypes.c_char)# 银行密码标志
,('SecuPwdFlag',ctypes.c_char)# 期货资金密码核对标志
,('TID',ctypes.c_int)# 交易ID
,('Digest',ctypes.c_char*36)# 摘要
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
,('LongCustomerName',ctypes.c_char*161)# 长客户姓名
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,CustomerName='',IdCardType='',IdentifiedCardNo='',Gender='',CountryCode='',CustType='',Address='',ZipCode='',Telephone='',MobilePhone='',Fax='',EMail='',MoneyAccountStatus='',BankAccount='',BankPassWord='',NewBankAccount='',NewBankPassWord='',AccountID='',Password='',BankAccType='',InstallID=0,VerifyCertNoFlag='',CurrencyID='',BrokerIDByBank='',BankPwdFlag='',SecuPwdFlag='',TID=0,Digest='',ErrorID=0,ErrorMsg='',LongCustomerName=''):
super(ChangeAccountField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.CustomerName=self._to_bytes(CustomerName)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.Gender=self._to_bytes(Gender)
self.CountryCode=self._to_bytes(CountryCode)
self.CustType=self._to_bytes(CustType)
self.Address=self._to_bytes(Address)
self.ZipCode=self._to_bytes(ZipCode)
self.Telephone=self._to_bytes(Telephone)
self.MobilePhone=self._to_bytes(MobilePhone)
self.Fax=self._to_bytes(Fax)
self.EMail=self._to_bytes(EMail)
self.MoneyAccountStatus=self._to_bytes(MoneyAccountStatus)
self.BankAccount=self._to_bytes(BankAccount)
self.BankPassWord=self._to_bytes(BankPassWord)
self.NewBankAccount=self._to_bytes(NewBankAccount)
self.NewBankPassWord=self._to_bytes(NewBankPassWord)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.BankAccType=self._to_bytes(BankAccType)
self.InstallID=int(InstallID)
self.VerifyCertNoFlag=self._to_bytes(VerifyCertNoFlag)
self.CurrencyID=self._to_bytes(CurrencyID)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.BankPwdFlag=self._to_bytes(BankPwdFlag)
self.SecuPwdFlag=self._to_bytes(SecuPwdFlag)
self.TID=int(TID)
self.Digest=self._to_bytes(Digest)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
self.LongCustomerName=self._to_bytes(LongCustomerName)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.CustomerName=self._to_bytes(i_tuple[13])
self.IdCardType=self._to_bytes(i_tuple[14])
self.IdentifiedCardNo=self._to_bytes(i_tuple[15])
self.Gender=self._to_bytes(i_tuple[16])
self.CountryCode=self._to_bytes(i_tuple[17])
self.CustType=self._to_bytes(i_tuple[18])
self.Address=self._to_bytes(i_tuple[19])
self.ZipCode=self._to_bytes(i_tuple[20])
self.Telephone=self._to_bytes(i_tuple[21])
self.MobilePhone=self._to_bytes(i_tuple[22])
self.Fax=self._to_bytes(i_tuple[23])
self.EMail=self._to_bytes(i_tuple[24])
self.MoneyAccountStatus=self._to_bytes(i_tuple[25])
self.BankAccount=self._to_bytes(i_tuple[26])
self.BankPassWord=self._to_bytes(i_tuple[27])
self.NewBankAccount=self._to_bytes(i_tuple[28])
self.NewBankPassWord=self._to_bytes(i_tuple[29])
self.AccountID=self._to_bytes(i_tuple[30])
self.Password=self._to_bytes(i_tuple[31])
self.BankAccType=self._to_bytes(i_tuple[32])
self.InstallID=int(i_tuple[33])
self.VerifyCertNoFlag=self._to_bytes(i_tuple[34])
self.CurrencyID=self._to_bytes(i_tuple[35])
self.BrokerIDByBank=self._to_bytes(i_tuple[36])
self.BankPwdFlag=self._to_bytes(i_tuple[37])
self.SecuPwdFlag=self._to_bytes(i_tuple[38])
self.TID=int(i_tuple[39])
self.Digest=self._to_bytes(i_tuple[40])
self.ErrorID=int(i_tuple[41])
self.ErrorMsg=self._to_bytes(i_tuple[42])
self.LongCustomerName=self._to_bytes(i_tuple[43])
class SecAgentACIDMapField(Base):
"""二级代理操作员银期权限"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('AccountID',ctypes.c_char*13)# 资金账户
,('CurrencyID',ctypes.c_char*4)# 币种
,('BrokerSecAgentID',ctypes.c_char*13)# 境外中介机构资金帐号
]
def __init__(self,BrokerID= '',UserID='',AccountID='',CurrencyID='',BrokerSecAgentID=''):
super(SecAgentACIDMapField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
self.BrokerSecAgentID=self._to_bytes(BrokerSecAgentID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
self.AccountID=self._to_bytes(i_tuple[3])
self.CurrencyID=self._to_bytes(i_tuple[4])
self.BrokerSecAgentID=self._to_bytes(i_tuple[5])
class QrySecAgentACIDMapField(Base):
"""二级代理操作员银期权限查询"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('AccountID',ctypes.c_char*13)# 资金账户
,('CurrencyID',ctypes.c_char*4)# 币种
]
def __init__(self,BrokerID= '',UserID='',AccountID='',CurrencyID=''):
super(QrySecAgentACIDMapField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.AccountID=self._to_bytes(AccountID)
self.CurrencyID=self._to_bytes(CurrencyID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
self.AccountID=self._to_bytes(i_tuple[3])
self.CurrencyID=self._to_bytes(i_tuple[4])
class UserRightsAssignField(Base):
"""灾备中心交易权限"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///应用单元代码
,('UserID',ctypes.c_char*16)# 用户代码
,('DRIdentityID',ctypes.c_int)# 交易中心代码
]
def __init__(self,BrokerID= '',UserID='',DRIdentityID=0):
super(UserRightsAssignField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.DRIdentityID=int(DRIdentityID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
self.DRIdentityID=int(i_tuple[3])
class BrokerUserRightAssignField(Base):
"""经济公司是否有在本标示的交易权限"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///应用单元代码
,('DRIdentityID',ctypes.c_int)# 交易中心代码
,('Tradeable',ctypes.c_int)# 能否交易
]
def __init__(self,BrokerID= '',DRIdentityID=0,Tradeable=0):
super(BrokerUserRightAssignField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.DRIdentityID=int(DRIdentityID)
self.Tradeable=int(Tradeable)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.DRIdentityID=int(i_tuple[2])
self.Tradeable=int(i_tuple[3])
class DRTransferField(Base):
"""灾备交易转换报文"""
_fields_ = [
('OrigDRIdentityID',ctypes.c_int)# ///原交易中心代码
,('DestDRIdentityID',ctypes.c_int)# 目标交易中心代码
,('OrigBrokerID',ctypes.c_char*11)# 原应用单元代码
,('DestBrokerID',ctypes.c_char*11)# 目标易用单元代码
]
def __init__(self,OrigDRIdentityID= 0,DestDRIdentityID=0,OrigBrokerID='',DestBrokerID=''):
super(DRTransferField,self).__init__()
self.OrigDRIdentityID=int(OrigDRIdentityID)
self.DestDRIdentityID=int(DestDRIdentityID)
self.OrigBrokerID=self._to_bytes(OrigBrokerID)
self.DestBrokerID=self._to_bytes(DestBrokerID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.OrigDRIdentityID=int(i_tuple[1])
self.DestDRIdentityID=int(i_tuple[2])
self.OrigBrokerID=self._to_bytes(i_tuple[3])
self.DestBrokerID=self._to_bytes(i_tuple[4])
class FensUserInfoField(Base):
"""Fens用户信息"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('LoginMode',ctypes.c_char)# 登录模式
]
def __init__(self,BrokerID= '',UserID='',LoginMode=''):
super(FensUserInfoField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.LoginMode=self._to_bytes(LoginMode)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
self.LoginMode=self._to_bytes(i_tuple[3])
class CurrTransferIdentityField(Base):
"""当前银期所属交易中心"""
_fields_ = [
('IdentityID',ctypes.c_int)# ///交易中心代码
]
def __init__(self,IdentityID= 0):
super(CurrTransferIdentityField,self).__init__()
self.IdentityID=int(IdentityID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.IdentityID=int(i_tuple[1])
class LoginForbiddenUserField(Base):
"""禁止登录用户"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
,('IPAddress',ctypes.c_char*16)# IP地址
]
def __init__(self,BrokerID= '',UserID='',IPAddress=''):
super(LoginForbiddenUserField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
self.IPAddress=self._to_bytes(IPAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
self.IPAddress=self._to_bytes(i_tuple[3])
class QryLoginForbiddenUserField(Base):
"""查询禁止登录用户"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('UserID',ctypes.c_char*16)# 用户代码
]
def __init__(self,BrokerID= '',UserID=''):
super(QryLoginForbiddenUserField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
class MulticastGroupInfoField(Base):
"""UDP组播组信息"""
_fields_ = [
('GroupIP',ctypes.c_char*16)# ///组播组IP地址
,('GroupPort',ctypes.c_int)# 组播组IP端口
,('SourceIP',ctypes.c_char*16)# 源地址
]
def __init__(self,GroupIP= '',GroupPort=0,SourceIP=''):
super(MulticastGroupInfoField,self).__init__()
self.GroupIP=self._to_bytes(GroupIP)
self.GroupPort=int(GroupPort)
self.SourceIP=self._to_bytes(SourceIP)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.GroupIP=self._to_bytes(i_tuple[1])
self.GroupPort=int(i_tuple[2])
self.SourceIP=self._to_bytes(i_tuple[3])
class TradingAccountReserveField(Base):
"""资金账户基本准备金"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Reserve',ctypes.c_double)# 基本准备金
,('CurrencyID',ctypes.c_char*4)# 币种代码
]
def __init__(self,BrokerID= '',AccountID='',Reserve=0.0,CurrencyID=''):
super(TradingAccountReserveField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.AccountID=self._to_bytes(AccountID)
self.Reserve=float(Reserve)
self.CurrencyID=self._to_bytes(CurrencyID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.AccountID=self._to_bytes(i_tuple[2])
self.Reserve=float(i_tuple[3])
self.CurrencyID=self._to_bytes(i_tuple[4])
class QryLoginForbiddenIPField(Base):
"""查询禁止登录IP"""
_fields_ = [
('IPAddress',ctypes.c_char*16)# ///IP地址
]
def __init__(self,IPAddress= ''):
super(QryLoginForbiddenIPField,self).__init__()
self.IPAddress=self._to_bytes(IPAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.IPAddress=self._to_bytes(i_tuple[1])
class QryIPListField(Base):
"""查询IP列表"""
_fields_ = [
('IPAddress',ctypes.c_char*16)# ///IP地址
]
def __init__(self,IPAddress= ''):
super(QryIPListField,self).__init__()
self.IPAddress=self._to_bytes(IPAddress)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.IPAddress=self._to_bytes(i_tuple[1])
class QryUserRightsAssignField(Base):
"""查询用户下单权限分配表"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///应用单元代码
,('UserID',ctypes.c_char*16)# 用户代码
]
def __init__(self,BrokerID= '',UserID=''):
super(QryUserRightsAssignField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.UserID=self._to_bytes(UserID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.UserID=self._to_bytes(i_tuple[2])
class ReserveOpenAccountConfirmField(Base):
"""银期预约开户确认请求"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('CustomerName',ctypes.c_char*161)# 客户姓名
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('Gender',ctypes.c_char)# 性别
,('CountryCode',ctypes.c_char*21)# 国家代码
,('CustType',ctypes.c_char)# 客户类型
,('Address',ctypes.c_char*101)# 地址
,('ZipCode',ctypes.c_char*7)# 邮编
,('Telephone',ctypes.c_char*41)# 电话号码
,('MobilePhone',ctypes.c_char*21)# 手机
,('Fax',ctypes.c_char*41)# 传真
,('EMail',ctypes.c_char*41)# 电子邮件
,('MoneyAccountStatus',ctypes.c_char)# 资金账户状态
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankPassWord',ctypes.c_char*41)# 银行密码
,('InstallID',ctypes.c_int)# 安装编号
,('VerifyCertNoFlag',ctypes.c_char)# 验证客户证件号码标志
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('Digest',ctypes.c_char*36)# 摘要
,('BankAccType',ctypes.c_char)# 银行帐号类型
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('TID',ctypes.c_int)# 交易ID
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('Password',ctypes.c_char*41)# 期货密码
,('BankReserveOpenSeq',ctypes.c_char*13)# 预约开户银行流水号
,('BookDate',ctypes.c_char*9)# 预约开户日期
,('BookPsw',ctypes.c_char*41)# 预约开户验证密码
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,CustomerName='',IdCardType='',IdentifiedCardNo='',Gender='',CountryCode='',CustType='',Address='',ZipCode='',Telephone='',MobilePhone='',Fax='',EMail='',MoneyAccountStatus='',BankAccount='',BankPassWord='',InstallID=0,VerifyCertNoFlag='',CurrencyID='',Digest='',BankAccType='',BrokerIDByBank='',TID=0,AccountID='',Password='',BankReserveOpenSeq='',BookDate='',BookPsw='',ErrorID=0,ErrorMsg=''):
super(ReserveOpenAccountConfirmField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.CustomerName=self._to_bytes(CustomerName)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.Gender=self._to_bytes(Gender)
self.CountryCode=self._to_bytes(CountryCode)
self.CustType=self._to_bytes(CustType)
self.Address=self._to_bytes(Address)
self.ZipCode=self._to_bytes(ZipCode)
self.Telephone=self._to_bytes(Telephone)
self.MobilePhone=self._to_bytes(MobilePhone)
self.Fax=self._to_bytes(Fax)
self.EMail=self._to_bytes(EMail)
self.MoneyAccountStatus=self._to_bytes(MoneyAccountStatus)
self.BankAccount=self._to_bytes(BankAccount)
self.BankPassWord=self._to_bytes(BankPassWord)
self.InstallID=int(InstallID)
self.VerifyCertNoFlag=self._to_bytes(VerifyCertNoFlag)
self.CurrencyID=self._to_bytes(CurrencyID)
self.Digest=self._to_bytes(Digest)
self.BankAccType=self._to_bytes(BankAccType)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.TID=int(TID)
self.AccountID=self._to_bytes(AccountID)
self.Password=self._to_bytes(Password)
self.BankReserveOpenSeq=self._to_bytes(BankReserveOpenSeq)
self.BookDate=self._to_bytes(BookDate)
self.BookPsw=self._to_bytes(BookPsw)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.CustomerName=self._to_bytes(i_tuple[13])
self.IdCardType=self._to_bytes(i_tuple[14])
self.IdentifiedCardNo=self._to_bytes(i_tuple[15])
self.Gender=self._to_bytes(i_tuple[16])
self.CountryCode=self._to_bytes(i_tuple[17])
self.CustType=self._to_bytes(i_tuple[18])
self.Address=self._to_bytes(i_tuple[19])
self.ZipCode=self._to_bytes(i_tuple[20])
self.Telephone=self._to_bytes(i_tuple[21])
self.MobilePhone=self._to_bytes(i_tuple[22])
self.Fax=self._to_bytes(i_tuple[23])
self.EMail=self._to_bytes(i_tuple[24])
self.MoneyAccountStatus=self._to_bytes(i_tuple[25])
self.BankAccount=self._to_bytes(i_tuple[26])
self.BankPassWord=self._to_bytes(i_tuple[27])
self.InstallID=int(i_tuple[28])
self.VerifyCertNoFlag=self._to_bytes(i_tuple[29])
self.CurrencyID=self._to_bytes(i_tuple[30])
self.Digest=self._to_bytes(i_tuple[31])
self.BankAccType=self._to_bytes(i_tuple[32])
self.BrokerIDByBank=self._to_bytes(i_tuple[33])
self.TID=int(i_tuple[34])
self.AccountID=self._to_bytes(i_tuple[35])
self.Password=self._to_bytes(i_tuple[36])
self.BankReserveOpenSeq=self._to_bytes(i_tuple[37])
self.BookDate=self._to_bytes(i_tuple[38])
self.BookPsw=self._to_bytes(i_tuple[39])
self.ErrorID=int(i_tuple[40])
self.ErrorMsg=self._to_bytes(i_tuple[41])
class ReserveOpenAccountField(Base):
"""银期预约开户"""
_fields_ = [
('TradeCode',ctypes.c_char*7)# ///业务功能码
,('BankID',ctypes.c_char*4)# 银行代码
,('BankBranchID',ctypes.c_char*5)# 银行分支机构代码
,('BrokerID',ctypes.c_char*11)# 期商代码
,('BrokerBranchID',ctypes.c_char*31)# 期商分支机构代码
,('TradeDate',ctypes.c_char*9)# 交易日期
,('TradeTime',ctypes.c_char*9)# 交易时间
,('BankSerial',ctypes.c_char*13)# 银行流水号
,('TradingDay',ctypes.c_char*9)# 交易系统日期
,('PlateSerial',ctypes.c_int)# 银期平台消息流水号
,('LastFragment',ctypes.c_char)# 最后分片标志
,('SessionID',ctypes.c_int)# 会话号
,('CustomerName',ctypes.c_char*161)# 客户姓名
,('IdCardType',ctypes.c_char)# 证件类型
,('IdentifiedCardNo',ctypes.c_char*51)# 证件号码
,('Gender',ctypes.c_char)# 性别
,('CountryCode',ctypes.c_char*21)# 国家代码
,('CustType',ctypes.c_char)# 客户类型
,('Address',ctypes.c_char*101)# 地址
,('ZipCode',ctypes.c_char*7)# 邮编
,('Telephone',ctypes.c_char*41)# 电话号码
,('MobilePhone',ctypes.c_char*21)# 手机
,('Fax',ctypes.c_char*41)# 传真
,('EMail',ctypes.c_char*41)# 电子邮件
,('MoneyAccountStatus',ctypes.c_char)# 资金账户状态
,('BankAccount',ctypes.c_char*41)# 银行帐号
,('BankPassWord',ctypes.c_char*41)# 银行密码
,('InstallID',ctypes.c_int)# 安装编号
,('VerifyCertNoFlag',ctypes.c_char)# 验证客户证件号码标志
,('CurrencyID',ctypes.c_char*4)# 币种代码
,('Digest',ctypes.c_char*36)# 摘要
,('BankAccType',ctypes.c_char)# 银行帐号类型
,('BrokerIDByBank',ctypes.c_char*33)# 期货公司银行编码
,('TID',ctypes.c_int)# 交易ID
,('ReserveOpenAccStas',ctypes.c_char)# 预约开户状态
,('ErrorID',ctypes.c_int)# 错误代码
,('ErrorMsg',ctypes.c_char*81)# 错误信息
]
def __init__(self,TradeCode= '',BankID='',BankBranchID='',BrokerID='',BrokerBranchID='',TradeDate='',TradeTime='',BankSerial='',TradingDay='',PlateSerial=0,LastFragment='',SessionID=0,CustomerName='',IdCardType='',IdentifiedCardNo='',Gender='',CountryCode='',CustType='',Address='',ZipCode='',Telephone='',MobilePhone='',Fax='',EMail='',MoneyAccountStatus='',BankAccount='',BankPassWord='',InstallID=0,VerifyCertNoFlag='',CurrencyID='',Digest='',BankAccType='',BrokerIDByBank='',TID=0,ReserveOpenAccStas='',ErrorID=0,ErrorMsg=''):
super(ReserveOpenAccountField,self).__init__()
self.TradeCode=self._to_bytes(TradeCode)
self.BankID=self._to_bytes(BankID)
self.BankBranchID=self._to_bytes(BankBranchID)
self.BrokerID=self._to_bytes(BrokerID)
self.BrokerBranchID=self._to_bytes(BrokerBranchID)
self.TradeDate=self._to_bytes(TradeDate)
self.TradeTime=self._to_bytes(TradeTime)
self.BankSerial=self._to_bytes(BankSerial)
self.TradingDay=self._to_bytes(TradingDay)
self.PlateSerial=int(PlateSerial)
self.LastFragment=self._to_bytes(LastFragment)
self.SessionID=int(SessionID)
self.CustomerName=self._to_bytes(CustomerName)
self.IdCardType=self._to_bytes(IdCardType)
self.IdentifiedCardNo=self._to_bytes(IdentifiedCardNo)
self.Gender=self._to_bytes(Gender)
self.CountryCode=self._to_bytes(CountryCode)
self.CustType=self._to_bytes(CustType)
self.Address=self._to_bytes(Address)
self.ZipCode=self._to_bytes(ZipCode)
self.Telephone=self._to_bytes(Telephone)
self.MobilePhone=self._to_bytes(MobilePhone)
self.Fax=self._to_bytes(Fax)
self.EMail=self._to_bytes(EMail)
self.MoneyAccountStatus=self._to_bytes(MoneyAccountStatus)
self.BankAccount=self._to_bytes(BankAccount)
self.BankPassWord=self._to_bytes(BankPassWord)
self.InstallID=int(InstallID)
self.VerifyCertNoFlag=self._to_bytes(VerifyCertNoFlag)
self.CurrencyID=self._to_bytes(CurrencyID)
self.Digest=self._to_bytes(Digest)
self.BankAccType=self._to_bytes(BankAccType)
self.BrokerIDByBank=self._to_bytes(BrokerIDByBank)
self.TID=int(TID)
self.ReserveOpenAccStas=self._to_bytes(ReserveOpenAccStas)
self.ErrorID=int(ErrorID)
self.ErrorMsg=self._to_bytes(ErrorMsg)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.TradeCode=self._to_bytes(i_tuple[1])
self.BankID=self._to_bytes(i_tuple[2])
self.BankBranchID=self._to_bytes(i_tuple[3])
self.BrokerID=self._to_bytes(i_tuple[4])
self.BrokerBranchID=self._to_bytes(i_tuple[5])
self.TradeDate=self._to_bytes(i_tuple[6])
self.TradeTime=self._to_bytes(i_tuple[7])
self.BankSerial=self._to_bytes(i_tuple[8])
self.TradingDay=self._to_bytes(i_tuple[9])
self.PlateSerial=int(i_tuple[10])
self.LastFragment=self._to_bytes(i_tuple[11])
self.SessionID=int(i_tuple[12])
self.CustomerName=self._to_bytes(i_tuple[13])
self.IdCardType=self._to_bytes(i_tuple[14])
self.IdentifiedCardNo=self._to_bytes(i_tuple[15])
self.Gender=self._to_bytes(i_tuple[16])
self.CountryCode=self._to_bytes(i_tuple[17])
self.CustType=self._to_bytes(i_tuple[18])
self.Address=self._to_bytes(i_tuple[19])
self.ZipCode=self._to_bytes(i_tuple[20])
self.Telephone=self._to_bytes(i_tuple[21])
self.MobilePhone=self._to_bytes(i_tuple[22])
self.Fax=self._to_bytes(i_tuple[23])
self.EMail=self._to_bytes(i_tuple[24])
self.MoneyAccountStatus=self._to_bytes(i_tuple[25])
self.BankAccount=self._to_bytes(i_tuple[26])
self.BankPassWord=self._to_bytes(i_tuple[27])
self.InstallID=int(i_tuple[28])
self.VerifyCertNoFlag=self._to_bytes(i_tuple[29])
self.CurrencyID=self._to_bytes(i_tuple[30])
self.Digest=self._to_bytes(i_tuple[31])
self.BankAccType=self._to_bytes(i_tuple[32])
self.BrokerIDByBank=self._to_bytes(i_tuple[33])
self.TID=int(i_tuple[34])
self.ReserveOpenAccStas=self._to_bytes(i_tuple[35])
self.ErrorID=int(i_tuple[36])
self.ErrorMsg=self._to_bytes(i_tuple[37])
class AccountPropertyField(Base):
"""银行账户属性"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('AccountID',ctypes.c_char*13)# 投资者帐号
,('BankID',ctypes.c_char*4)# 银行统一标识类型
,('BankAccount',ctypes.c_char*41)# 银行账户
,('OpenName',ctypes.c_char*101)# 银行账户的开户人名称
,('OpenBank',ctypes.c_char*101)# 银行账户的开户行
,('IsActive',ctypes.c_int)# 是否活跃
,('AccountSourceType',ctypes.c_char)# 账户来源
,('OpenDate',ctypes.c_char*9)# 开户日期
,('CancelDate',ctypes.c_char*9)# 注销日期
,('OperatorID',ctypes.c_char*65)# 录入员代码
,('OperateDate',ctypes.c_char*9)# 录入日期
,('OperateTime',ctypes.c_char*9)# 录入时间
,('CurrencyID',ctypes.c_char*4)# 币种代码
]
def __init__(self,BrokerID= '',AccountID='',BankID='',BankAccount='',OpenName='',OpenBank='',IsActive=0,AccountSourceType='',OpenDate='',CancelDate='',OperatorID='',OperateDate='',OperateTime='',CurrencyID=''):
super(AccountPropertyField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.AccountID=self._to_bytes(AccountID)
self.BankID=self._to_bytes(BankID)
self.BankAccount=self._to_bytes(BankAccount)
self.OpenName=self._to_bytes(OpenName)
self.OpenBank=self._to_bytes(OpenBank)
self.IsActive=int(IsActive)
self.AccountSourceType=self._to_bytes(AccountSourceType)
self.OpenDate=self._to_bytes(OpenDate)
self.CancelDate=self._to_bytes(CancelDate)
self.OperatorID=self._to_bytes(OperatorID)
self.OperateDate=self._to_bytes(OperateDate)
self.OperateTime=self._to_bytes(OperateTime)
self.CurrencyID=self._to_bytes(CurrencyID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.AccountID=self._to_bytes(i_tuple[2])
self.BankID=self._to_bytes(i_tuple[3])
self.BankAccount=self._to_bytes(i_tuple[4])
self.OpenName=self._to_bytes(i_tuple[5])
self.OpenBank=self._to_bytes(i_tuple[6])
self.IsActive=int(i_tuple[7])
self.AccountSourceType=self._to_bytes(i_tuple[8])
self.OpenDate=self._to_bytes(i_tuple[9])
self.CancelDate=self._to_bytes(i_tuple[10])
self.OperatorID=self._to_bytes(i_tuple[11])
self.OperateDate=self._to_bytes(i_tuple[12])
self.OperateTime=self._to_bytes(i_tuple[13])
self.CurrencyID=self._to_bytes(i_tuple[14])
class QryCurrDRIdentityField(Base):
"""查询当前交易中心"""
_fields_ = [
('DRIdentityID',ctypes.c_int)# ///交易中心代码
]
def __init__(self,DRIdentityID= 0):
super(QryCurrDRIdentityField,self).__init__()
self.DRIdentityID=int(DRIdentityID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.DRIdentityID=int(i_tuple[1])
class CurrDRIdentityField(Base):
"""当前交易中心"""
_fields_ = [
('DRIdentityID',ctypes.c_int)# ///交易中心代码
]
def __init__(self,DRIdentityID= 0):
super(CurrDRIdentityField,self).__init__()
self.DRIdentityID=int(DRIdentityID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.DRIdentityID=int(i_tuple[1])
class QrySecAgentCheckModeField(Base):
"""查询二级代理商资金校验模式"""
_fields_ = [
('BrokerID',ctypes.c_char*11)# ///经纪公司代码
,('InvestorID',ctypes.c_char*13)# 投资者代码
]
def __init__(self,BrokerID= '',InvestorID=''):
super(QrySecAgentCheckModeField,self).__init__()
self.BrokerID=self._to_bytes(BrokerID)
self.InvestorID=self._to_bytes(InvestorID)
def towhere(self):
l_where = ""
l_dict = self.to_dict()
for k,v in l_dict.items():
if not v is None and len(self._to_str(v)) > 0:
if len(l_where) > 0:
l_where = l_where + " and " + k + "=" + self._to_str4where(v)
else:
l_where = k + "=" + self._to_str4where(v)
if len(l_where) > 0:
l_where = " WHERE " + l_where
return l_where
def from_tuple(self, i_tuple):
self.BrokerID=self._to_bytes(i_tuple[1])
self.InvestorID=self._to_bytes(i_tuple[2]) | ytp1 | /ytp1-6.3.12-cp36-cp36m-win_amd64.whl/ptp/py_ApiStructure.py | py_ApiStructure.py |
import cProfile
import pstats
import io
import os
import time,datetime
import configparser
import sys
from ptp import py_ApiStructure
from ptp import py_base
from ptp import CythonLib
from ptp.CythonLib import printString
from ptp.CythonLib import printNumber
import cfg.ptp_env as myEnv
import cfg.ptp_can_change_env as myDEnv #需要动态实时变化的
from ptp.TraderApi import TraderApiWrapper
class py_CtpTrader(TraderApiWrapper):
def __init__(self, server
, broker_id
, investor_id
, password
, i_md_queue
, pszFlowPath=""):
try:
#Profiler
if myEnv.Profiler == 1:
self.Profiler = cProfile.Profile()
self.Profiler.enable()
str_date_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y%m%d_%H%M%S")
self.pid_file = "log/PID_Trader.%s.%s.log"%(os.getpid(),str_date_time)
l_pid_file = open(self.pid_file, "w", encoding="utf-8")
l_pid_file.write(str(os.getpid()))
l_pid_file.close()
self.PTP_Algos = CythonLib.CPTPAlgos()
#调用情况
self.m_started = 0
self.req_call = {}
#基本信息
self.broker_id = broker_id
self.investor_id = investor_id
self.password = password
self.trader_server = server
self.pszFlowPath = pszFlowPath
self.PrivateSubscribeTopic = myEnv.PrivateSubscribeTopic
self.PublicSubscribeTopic = myEnv.PublicSubscribeTopic
#进程间通信
self.md_queue = i_md_queue
self.m_md_sum = 0
#基础配置
self.config = configparser.ConfigParser()
self.config.read("cfg/ptp.ini",encoding="utf-8")
#0:实盘撮合成交 1:PTP撮合成交(价格合适就成交,全量成交)
self.Trader_Rule = int(self.config.get("TRADE_MODE", "Trader_Rule"))
nRetVal = self.Init_Base()
if nRetVal != 0:
myEnv.logger.error("py_CtpTrader Init_Base failed.")
sys.exit(1)
#"""
#0:实盘, 1:模拟撮合
#准备基础数据
if self.Trader_Rule == 0:
l_found=0
for the_server in server:
info_list = the_server.split(":")
ip = info_list[1][2:]
port = int(info_list[2])
if not py_base.check_service(ip,port):
print(the_server + " is closed")
else:
print(the_server + " is OK!")
l_found=1
if l_found == 0:
print("There is no active Trader server")
sys.exit(1)
super(py_CtpTrader, self).Init_Net() # C++的RegisterSpi和Init都封装在父类的Init中
#get 基础数据(Order)
l_pQryOrder = py_ApiStructure.QryOrderField(BrokerID = self.broker_id,
InvestorID = self.investor_id
)
l_retVal = -1
while l_retVal != 0:
time.sleep(1)
myEnv.logger.info("ready to ReqQryOrder...")
l_retVal = self.ReqQryOrder(pQryOrder=l_pQryOrder)
#get 基础数据(Position)
l_pQryPos = py_ApiStructure.QryInvestorPositionField(BrokerID = self.broker_id,
InvestorID = self.investor_id
)
l_retVal = -1
while l_retVal != 0:
time.sleep(1)
myEnv.logger.info("ready to ReqQryInvestorPosition...")
l_retVal = self.ReqQryInvestorPosition(pQryInvestorPosition=l_pQryPos)
#get 基础数据(资金)
pQryTradingAccount = py_ApiStructure.QryTradingAccountField(BrokerID = self.broker_id,
InvestorID = self.investor_id,
CurrencyID = "CNY",
BizType = "1"
)
l_retVal = -1
while l_retVal != 0:
time.sleep(1)
myEnv.logger.info("ready to ReqQryTradingAccount...")
l_retVal = self.ReqQryTradingAccount(pQryTradingAccount)
#get 基础数据(instrument)
l_dict = {}
for it_instrumentid in myDEnv.my_instrument_id:
InstrumentField = py_ApiStructure.QryInstrumentField(InstrumentID=it_instrumentid) #InstrumentID=it_instrumentid
l_retVal = -1
while True:
time.sleep(1)
myEnv.logger.info("ready to ReqQryInstrument...")
l_retVal = self.ReqQryInstrument(pQryInstrument=InstrumentField)
if l_retVal == 0:
l_dict = self.get_InstrumentAttr(it_instrumentid)
if not l_dict is None and len(l_dict)>0:
break
#启动完成
self.m_started = 1
myEnv.logger.info("交易启动完毕(broker_id:%s,investor_id:%s,server:%s)"%(broker_id,investor_id,server))
except Exception as err:
myEnv.logger.error("py_CtpTrader init failed.", exc_info=True)
def __del__(self):
if myEnv.Profiler == 1:
self.Profiler.disable()
s = io.StringIO()
ps = pstats.Stats(self.Profiler, stream=s).sort_stats("cumulative")
ps.print_stats()
pr_file = open("log/Profiler_Trader.%s.log"%os.getpid(), "w", encoding="utf-8")
pr_file.write(s.getvalue())
pr_file.close()
if os.path.exists(self.pid_file):
os.remove(self.pid_file)
def Release(self):
super(py_CtpTrader, self).Release()
def Join(self):
while True:
#print(time.localtime( time.time() ))
time.sleep(1)
return super(py_CtpTrader, self).Join()
def GetTradingDay(self):
"""
获取当前交易日
@retrun 获取到的交易日
@remark 只有登录成功后,才能得到正确的交易日
"""
day = super(py_CtpTrader, self).GetTradingDay()
if day is None:
return None;
else:
return day.decode(encoding="gb18030", errors="ignore")
def OnRspError(self, pRspInfo, nRequestID, bIsLast):
"""
:param info:
:return:
"""
if pRspInfo is None:
return ;
if pRspInfo.ErrorID != 0:
print("RequestID=%s ErrorID=%d, ErrorMsg=%s",
nRequestID, pRspInfo.ErrorID, pRspInfo.ErrorMsg.decode(encoding="gb18030", errors="ignore"))
return pRspInfo.ErrorID != 0
def RegisterNameServer(self, pszNsAddress):
"""
注册名字服务器网络地址
@param pszNsAddress:名字服务器网络地址。
@remark 网络地址的格式为:“protocol:
ipaddress:port”,如:”tcp:
127.0.0.1:12001”。
@remark “tcp”代表传输协议,“127.0.0.1”代表服务器地址。”12001”代表服务器端口号。
@remark RegisterNameServer优先于RegisterFront
"""
super(py_CtpTrader, self).RegisterNameServer(pszNsAddress.encode())
def RegisterFensUserInfo(self, pFensUserInfo):
"""
注册名字服务器用户信息
@param pFensUserInfo:用户信息。
"""
super(py_CtpTrader, self).RegisterFensUserInfo(pFensUserInfo)
def SubscribePrivateTopic(self, nResumeType: int):
"""
订阅私有流。
@param nResumeType 私有流重传方式
THOST_TERT_RESTART:0,从本交易日开始重传
THOST_TERT_RESUME:1,从上次收到的续传
THOST_TERT_QUICK:2,只传送登录后私有流的内容
@remark 该方法要在Init方法前调用。若不调用则不会收到私有流的数据。
"""
super(py_CtpTrader, self).SubscribePrivateTopic(nResumeType)
def SubscribePublicTopic(self, nResumeType: int):
"""
订阅公共流。
@param nResumeType 公共流重传方式
THOST_TERT_RESTART:0,从本交易日开始重传
THOST_TERT_RESUME:1,从上次收到的续传
THOST_TERT_QUICK:2只传送登录后公共流的内容
@remark 该方法要在Init方法前调用。若不调用则不会收到公共流的数据。
"""
super(py_CtpTrader, self).SubscribePublicTopic(nResumeType)
###################################################
def OnHeartBeatWarning(self, nTimeLapse):
"""心跳超时警告。当长时间未收到报文时,该方法被调用。
@param nTimeLapse 距离上次接收报文的时间
"""
print("on OnHeartBeatWarning time: ", nTimeLapse)
# 当客户端与交易后台通信连接断开时,该方法被调用。当发生这个情况后,API会自动重新连接,客户端可不做处理。
# @param nReason 错误原因
# 0x1001 网络读失败
# 0x1002 网络写失败
# 0x2001 接收心跳超时
# 0x2002 发送心跳失败
# 0x2003 收到错误报文
def OnFrontDisconnected(self, nReason):
print("on FrontDisConnected disconnected", nReason)
def OnFrontConnected(self):
#连接回调后自动登录,所以不需要单独调用登录接口
req = py_ApiStructure.ReqUserLoginField(BrokerID=self.broker_id,
UserID=self.investor_id,
Password=self.password)
self.ReqUserLogin(req)
def OnRspUserLogin(self, pRspUserLogin, pRspInfo, nRequestID, bIsLast):
if bIsLast == True:
self.req_call["UserLogin"] = 1
if pRspInfo.ErrorID != 0:
print("登录CTP柜台失败. Server return error_id=%s msg:%s",
pRspInfo.ErrorID, pRspInfo.ErrorMsg.decode(encoding="gb18030", errors="ignore"))
else:
#登陆成功自动确认结算结果
print("py_CtpTrader Server user login successfully")
req = py_ApiStructure.SettlementInfoConfirmField(BrokerID = self.broker_id,InvestorID=self.investor_id)
self.ReqSettlementInfoConfirm(req)
def ReqAuthenticate(self, pReqAuthenticate):
'''
///客户端认证请求
'''
"""CThostFtdcReqAuthenticateField
l_CThostFtdcReqAuthenticateField=py_ApiStructure.ReqAuthenticateField(
BrokerID ='?' # ///经纪公司代码
,UserID ='?' # ///用户代码
,UserProductInfo ='?' # ///用户端产品信息
,AuthCode ='?' # ///认证码
)
#"""
self.req_call['Authenticate'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqAuthenticate(pReqAuthenticate,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqAuthenticate(pReqAuthenticate,self.Inc_RequestID() )
def ReqUserLogin(self, pReqUserLogin):
'''
///用户登录请求
'''
"""CThostFtdcReqUserLoginField
l_CThostFtdcReqUserLoginField=py_ApiStructure.ReqUserLoginField(
TradingDay ='?' # ///交易日
,BrokerID ='?' # ///经纪公司代码
,UserID ='?' # ///用户代码
,Password ='?' # ///密码
,UserProductInfo ='?' # ///用户端产品信息
,InterfaceProductInfo ='?' # ///接口端产品信息
,ProtocolInfo ='?' # ///协议信息
,MacAddress ='?' # ///Mac地址
,OneTimePassword ='?' # ///动态密码
,ClientIPAddress ='?' # ///终端IP地址
,LoginRemark ='?' # ///登录备注
)
#"""
self.req_call['UserLogin'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqUserLogin(pReqUserLogin,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqUserLogin(pReqUserLogin,self.Inc_RequestID() )
def ReqUserLogout(self, pUserLogout):
'''
///登出请求
'''
"""CThostFtdcUserLogoutField
l_CThostFtdcUserLogoutField=py_ApiStructure.UserLogoutField(
BrokerID ='?' # ///经纪公司代码
,UserID ='?' # ///用户代码
)
#"""
self.req_call['UserLogout'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqUserLogout(pUserLogout,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqUserLogout(pUserLogout,self.Inc_RequestID() )
def ReqUserPasswordUpdate(self, pUserPasswordUpdate):
'''
///用户口令更新请求
'''
"""CThostFtdcUserPasswordUpdateField
l_CThostFtdcUserPasswordUpdateField=py_ApiStructure.UserPasswordUpdateField(
BrokerID ='?' # ///经纪公司代码
,UserID ='?' # ///用户代码
,OldPassword ='?' # ///原来的口令
,NewPassword ='?' # ///新的口令
)
#"""
self.req_call['UserPasswordUpdate'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqUserPasswordUpdate(pUserPasswordUpdate,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqUserPasswordUpdate(pUserPasswordUpdate,self.Inc_RequestID() )
def ReqTradingAccountPasswordUpdate(self, pTradingAccountPasswordUpdate):
'''
///资金账户口令更新请求
'''
"""CThostFtdcTradingAccountPasswordUpdateField
l_CThostFtdcTradingAccountPasswordUpdateField=py_ApiStructure.TradingAccountPasswordUpdateField(
BrokerID ='?' # ///经纪公司代码
,AccountID ='?' # ///投资者帐号
,OldPassword ='?' # ///原来的口令
,NewPassword ='?' # ///新的口令
,CurrencyID ='?' # ///币种代码
)
#"""
self.req_call['TradingAccountPasswordUpdate'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqTradingAccountPasswordUpdate(pTradingAccountPasswordUpdate,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqTradingAccountPasswordUpdate(pTradingAccountPasswordUpdate,self.Inc_RequestID() )
def ReqUserLogin2(self, pReqUserLogin):
'''
///登录请求2
'''
"""CThostFtdcReqUserLoginField
l_CThostFtdcReqUserLoginField=py_ApiStructure.ReqUserLoginField(
TradingDay ='?' # ///交易日
,BrokerID ='?' # ///经纪公司代码
,UserID ='?' # ///用户代码
,Password ='?' # ///密码
,UserProductInfo ='?' # ///用户端产品信息
,InterfaceProductInfo ='?' # ///接口端产品信息
,ProtocolInfo ='?' # ///协议信息
,MacAddress ='?' # ///Mac地址
,OneTimePassword ='?' # ///动态密码
,ClientIPAddress ='?' # ///终端IP地址
,LoginRemark ='?' # ///登录备注
)
#"""
self.req_call['UserLogin2'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqUserLogin2(pReqUserLogin,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqUserLogin2(pReqUserLogin,self.Inc_RequestID() )
def ReqUserPasswordUpdate2(self, pUserPasswordUpdate):
'''
///用户口令更新请求2
'''
"""CThostFtdcUserPasswordUpdateField
l_CThostFtdcUserPasswordUpdateField=py_ApiStructure.UserPasswordUpdateField(
BrokerID ='?' # ///经纪公司代码
,UserID ='?' # ///用户代码
,OldPassword ='?' # ///原来的口令
,NewPassword ='?' # ///新的口令
)
#"""
self.req_call['UserPasswordUpdate2'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqUserPasswordUpdate2(pUserPasswordUpdate,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqUserPasswordUpdate2(pUserPasswordUpdate,self.Inc_RequestID() )
def ReqOrderInsert(self, pInputOrder,express="",md_LastPrice=0):
'''
///报单录入请求
'''
"""CThostFtdcInputOrderField
l_CThostFtdcInputOrderField=py_ApiStructure.InputOrderField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,OrderRef ='?' # ///报单引用
,UserID ='?' # ///用户代码
,OrderPriceType ='?' # ///报单价格条件
,Direction ='?' # ///买卖方向
,CombOffsetFlag ='?' # ///组合开平标志
,CombHedgeFlag ='?' # ///组合投机套保标志
,LimitPrice ='?' # ///价格
,VolumeTotalOriginal ='?' # ///数量
,TimeCondition ='?' # ///有效期类型
,GTDDate ='?' # ///GTD日期
,VolumeCondition ='?' # ///成交量类型
,MinVolume ='?' # ///最小成交量
,ContingentCondition ='?' # ///触发条件
,StopPrice ='?' # ///止损价
,ForceCloseReason ='?' # ///强平原因
,IsAutoSuspend ='?' # ///自动挂起标志
,BusinessUnit ='?' # ///业务单元
,RequestID ='?' # ///请求编号
,UserForceClose ='?' # ///用户强评标志
,IsSwapOrder ='?' # ///互换单标志
,ExchangeID ='?' # ///交易所代码
,InvestUnitID ='?' # ///投资单元代码
,AccountID ='?' # ///资金账号
,CurrencyID ='?' # ///币种代码
,ClientID ='?' # ///交易编码
,IPAddress ='?' # ///IP地址
,MacAddress ='?' # ///Mac地址
)
#"""
self.req_call['OrderInsert'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqOrderInsert(pInputOrder,self.Inc_RequestID() ,express,md_LastPrice)
else:
return self.PTP_Algos.ReqOrderInsert(pInputOrder,self.Inc_RequestID() ,express,md_LastPrice)
def ReqParkedOrderInsert(self, pParkedOrder):
'''
///预埋单录入请求
'''
"""CThostFtdcParkedOrderField
l_CThostFtdcParkedOrderField=py_ApiStructure.ParkedOrderField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,OrderRef ='?' # ///报单引用
,UserID ='?' # ///用户代码
,OrderPriceType ='?' # ///报单价格条件
,Direction ='?' # ///买卖方向
,CombOffsetFlag ='?' # ///组合开平标志
,CombHedgeFlag ='?' # ///组合投机套保标志
,LimitPrice ='?' # ///价格
,VolumeTotalOriginal ='?' # ///数量
,TimeCondition ='?' # ///有效期类型
,GTDDate ='?' # ///GTD日期
,VolumeCondition ='?' # ///成交量类型
,MinVolume ='?' # ///最小成交量
,ContingentCondition ='?' # ///触发条件
,StopPrice ='?' # ///止损价
,ForceCloseReason ='?' # ///强平原因
,IsAutoSuspend ='?' # ///自动挂起标志
,BusinessUnit ='?' # ///业务单元
,RequestID ='?' # ///请求编号
,UserForceClose ='?' # ///用户强评标志
,ExchangeID ='?' # ///交易所代码
,ParkedOrderID ='?' # ///预埋报单编号
,UserType ='?' # ///用户类型
,Status ='?' # ///预埋单状态
,ErrorID ='?' # ///错误代码
,ErrorMsg ='?' # ///错误信息
,IsSwapOrder ='?' # ///互换单标志
,AccountID ='?' # ///资金账号
,CurrencyID ='?' # ///币种代码
,ClientID ='?' # ///交易编码
,InvestUnitID ='?' # ///投资单元代码
,IPAddress ='?' # ///IP地址
,MacAddress ='?' # ///Mac地址
)
#"""
self.req_call['ParkedOrderInsert'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqParkedOrderInsert(pParkedOrder,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqParkedOrderInsert(pParkedOrder,self.Inc_RequestID() )
def ReqParkedOrderAction(self, pParkedOrderAction):
'''
///预埋撤单录入请求
'''
"""CThostFtdcParkedOrderActionField
l_CThostFtdcParkedOrderActionField=py_ApiStructure.ParkedOrderActionField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,OrderActionRef ='?' # ///报单操作引用
,OrderRef ='?' # ///报单引用
,RequestID ='?' # ///请求编号
,FrontID ='?' # ///前置编号
,SessionID ='?' # ///会话编号
,ExchangeID ='?' # ///交易所代码
,OrderSysID ='?' # ///报单编号
,ActionFlag ='?' # ///操作标志
,LimitPrice ='?' # ///价格
,VolumeChange ='?' # ///数量变化
,UserID ='?' # ///用户代码
,InstrumentID ='?' # ///合约代码
,ParkedOrderActionID ='?' # ///预埋撤单单编号
,UserType ='?' # ///用户类型
,Status ='?' # ///预埋撤单状态
,ErrorID ='?' # ///错误代码
,ErrorMsg ='?' # ///错误信息
,InvestUnitID ='?' # ///投资单元代码
,IPAddress ='?' # ///IP地址
,MacAddress ='?' # ///Mac地址
)
#"""
self.req_call['ParkedOrderAction'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqParkedOrderAction(pParkedOrderAction,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqParkedOrderAction(pParkedOrderAction,self.Inc_RequestID() )
def ReqOrderAction(self, pInputOrderAction):
'''
///报单操作请求
'''
"""CThostFtdcInputOrderActionField
l_CThostFtdcInputOrderActionField=py_ApiStructure.InputOrderActionField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,OrderActionRef ='?' # ///报单操作引用
,OrderRef ='?' # ///报单引用
,RequestID ='?' # ///请求编号
,FrontID ='?' # ///前置编号
,SessionID ='?' # ///会话编号
,ExchangeID ='?' # ///交易所代码
,OrderSysID ='?' # ///报单编号
,ActionFlag ='?' # ///操作标志
,LimitPrice ='?' # ///价格
,VolumeChange ='?' # ///数量变化
,UserID ='?' # ///用户代码
,InstrumentID ='?' # ///合约代码
,InvestUnitID ='?' # ///投资单元代码
,IPAddress ='?' # ///IP地址
,MacAddress ='?' # ///Mac地址
)
#"""
self.req_call['OrderAction'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqOrderAction(pInputOrderAction,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqOrderAction(pInputOrderAction,self.Inc_RequestID() )
def ReqQueryMaxOrderVolume(self, pQueryMaxOrderVolume):
'''
///查询最大报单数量请求
'''
"""CThostFtdcQueryMaxOrderVolumeField
l_CThostFtdcQueryMaxOrderVolumeField=py_ApiStructure.QueryMaxOrderVolumeField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,Direction ='?' # ///买卖方向
,OffsetFlag ='?' # ///开平标志
,HedgeFlag ='?' # ///投机套保标志
,MaxVolume ='?' # ///最大允许报单数量
,ExchangeID ='?' # ///交易所代码
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QueryMaxOrderVolume'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQueryMaxOrderVolume(pQueryMaxOrderVolume,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQueryMaxOrderVolume(pQueryMaxOrderVolume,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQueryMaxOrderVolume(it_ret_val, None, nRequestID, True)
return 0
def ReqSettlementInfoConfirm(self, pSettlementInfoConfirm):
'''
///投资者结算结果确认
'''
"""CThostFtdcSettlementInfoConfirmField
l_CThostFtdcSettlementInfoConfirmField=py_ApiStructure.SettlementInfoConfirmField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,ConfirmDate ='?' # ///确认日期
,ConfirmTime ='?' # ///确认时间
,SettlementID ='?' # ///结算编号
,AccountID ='?' # ///投资者帐号
,CurrencyID ='?' # ///币种代码
)
#"""
self.req_call['SettlementInfoConfirm'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqSettlementInfoConfirm(pSettlementInfoConfirm,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqSettlementInfoConfirm(pSettlementInfoConfirm,self.Inc_RequestID() )
def ReqRemoveParkedOrder(self, pRemoveParkedOrder):
'''
///请求删除预埋单
'''
"""CThostFtdcRemoveParkedOrderField
l_CThostFtdcRemoveParkedOrderField=py_ApiStructure.RemoveParkedOrderField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,ParkedOrderID ='?' # ///预埋报单编号
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['RemoveParkedOrder'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqRemoveParkedOrder(pRemoveParkedOrder,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqRemoveParkedOrder(pRemoveParkedOrder,self.Inc_RequestID() )
def ReqRemoveParkedOrderAction(self, pRemoveParkedOrderAction):
'''
///请求删除预埋撤单
'''
"""CThostFtdcRemoveParkedOrderActionField
l_CThostFtdcRemoveParkedOrderActionField=py_ApiStructure.RemoveParkedOrderActionField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,ParkedOrderActionID ='?' # ///预埋撤单编号
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['RemoveParkedOrderAction'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqRemoveParkedOrderAction(pRemoveParkedOrderAction,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqRemoveParkedOrderAction(pRemoveParkedOrderAction,self.Inc_RequestID() )
def ReqExecOrderInsert(self, pInputExecOrder):
'''
///执行宣告录入请求
'''
"""CThostFtdcInputExecOrderField
l_CThostFtdcInputExecOrderField=py_ApiStructure.InputExecOrderField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,ExecOrderRef ='?' # ///执行宣告引用
,UserID ='?' # ///用户代码
,Volume ='?' # ///数量
,RequestID ='?' # ///请求编号
,BusinessUnit ='?' # ///业务单元
,OffsetFlag ='?' # ///开平标志
,HedgeFlag ='?' # ///投机套保标志
,ActionType ='?' # ///执行类型
,PosiDirection ='?' # ///保留头寸申请的持仓方向
,ReservePositionFlag ='?' # ///期权行权后是否保留期货头寸的标记,该字段已废弃
,CloseFlag ='?' # ///期权行权后生成的头寸是否自动平仓
,ExchangeID ='?' # ///交易所代码
,InvestUnitID ='?' # ///投资单元代码
,AccountID ='?' # ///资金账号
,CurrencyID ='?' # ///币种代码
,ClientID ='?' # ///交易编码
,IPAddress ='?' # ///IP地址
,MacAddress ='?' # ///Mac地址
)
#"""
self.req_call['ExecOrderInsert'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqExecOrderInsert(pInputExecOrder,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqExecOrderInsert(pInputExecOrder,self.Inc_RequestID() )
def ReqExecOrderAction(self, pInputExecOrderAction):
'''
///执行宣告操作请求
'''
"""CThostFtdcInputExecOrderActionField
l_CThostFtdcInputExecOrderActionField=py_ApiStructure.InputExecOrderActionField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,ExecOrderActionRef ='?' # ///执行宣告操作引用
,ExecOrderRef ='?' # ///执行宣告引用
,RequestID ='?' # ///请求编号
,FrontID ='?' # ///前置编号
,SessionID ='?' # ///会话编号
,ExchangeID ='?' # ///交易所代码
,ExecOrderSysID ='?' # ///执行宣告操作编号
,ActionFlag ='?' # ///操作标志
,UserID ='?' # ///用户代码
,InstrumentID ='?' # ///合约代码
,InvestUnitID ='?' # ///投资单元代码
,IPAddress ='?' # ///IP地址
,MacAddress ='?' # ///Mac地址
)
#"""
self.req_call['ExecOrderAction'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqExecOrderAction(pInputExecOrderAction,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqExecOrderAction(pInputExecOrderAction,self.Inc_RequestID() )
def ReqForQuoteInsert(self, pInputForQuote):
'''
///询价录入请求
'''
"""CThostFtdcInputForQuoteField
l_CThostFtdcInputForQuoteField=py_ApiStructure.InputForQuoteField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,ForQuoteRef ='?' # ///询价引用
,UserID ='?' # ///用户代码
,ExchangeID ='?' # ///交易所代码
,InvestUnitID ='?' # ///投资单元代码
,IPAddress ='?' # ///IP地址
,MacAddress ='?' # ///Mac地址
)
#"""
self.req_call['ForQuoteInsert'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqForQuoteInsert(pInputForQuote,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqForQuoteInsert(pInputForQuote,self.Inc_RequestID() )
def ReqQuoteInsert(self, pInputQuote):
'''
///报价录入请求
'''
"""CThostFtdcInputQuoteField
l_CThostFtdcInputQuoteField=py_ApiStructure.InputQuoteField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,QuoteRef ='?' # ///报价引用
,UserID ='?' # ///用户代码
,AskPrice ='?' # ///卖价格
,BidPrice ='?' # ///买价格
,AskVolume ='?' # ///卖数量
,BidVolume ='?' # ///买数量
,RequestID ='?' # ///请求编号
,BusinessUnit ='?' # ///业务单元
,AskOffsetFlag ='?' # ///卖开平标志
,BidOffsetFlag ='?' # ///买开平标志
,AskHedgeFlag ='?' # ///卖投机套保标志
,BidHedgeFlag ='?' # ///买投机套保标志
,AskOrderRef ='?' # ///衍生卖报单引用
,BidOrderRef ='?' # ///衍生买报单引用
,ForQuoteSysID ='?' # ///应价编号
,ExchangeID ='?' # ///交易所代码
,InvestUnitID ='?' # ///投资单元代码
,ClientID ='?' # ///交易编码
,IPAddress ='?' # ///IP地址
,MacAddress ='?' # ///Mac地址
)
#"""
self.req_call['QuoteInsert'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQuoteInsert(pInputQuote,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqQuoteInsert(pInputQuote,self.Inc_RequestID() )
def ReqQuoteAction(self, pInputQuoteAction):
'''
///报价操作请求
'''
"""CThostFtdcInputQuoteActionField
l_CThostFtdcInputQuoteActionField=py_ApiStructure.InputQuoteActionField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,QuoteActionRef ='?' # ///报价操作引用
,QuoteRef ='?' # ///报价引用
,RequestID ='?' # ///请求编号
,FrontID ='?' # ///前置编号
,SessionID ='?' # ///会话编号
,ExchangeID ='?' # ///交易所代码
,QuoteSysID ='?' # ///报价操作编号
,ActionFlag ='?' # ///操作标志
,UserID ='?' # ///用户代码
,InstrumentID ='?' # ///合约代码
,InvestUnitID ='?' # ///投资单元代码
,ClientID ='?' # ///交易编码
,IPAddress ='?' # ///IP地址
,MacAddress ='?' # ///Mac地址
)
#"""
self.req_call['QuoteAction'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQuoteAction(pInputQuoteAction,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqQuoteAction(pInputQuoteAction,self.Inc_RequestID() )
def ReqBatchOrderAction(self, pInputBatchOrderAction):
'''
///批量报单操作请求
'''
"""CThostFtdcInputBatchOrderActionField
l_CThostFtdcInputBatchOrderActionField=py_ApiStructure.InputBatchOrderActionField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,OrderActionRef ='?' # ///报单操作引用
,RequestID ='?' # ///请求编号
,FrontID ='?' # ///前置编号
,SessionID ='?' # ///会话编号
,ExchangeID ='?' # ///交易所代码
,UserID ='?' # ///用户代码
,InvestUnitID ='?' # ///投资单元代码
,IPAddress ='?' # ///IP地址
,MacAddress ='?' # ///Mac地址
)
#"""
self.req_call['BatchOrderAction'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqBatchOrderAction(pInputBatchOrderAction,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqBatchOrderAction(pInputBatchOrderAction,self.Inc_RequestID() )
def ReqOptionSelfCloseInsert(self, pInputOptionSelfClose):
'''
///期权自对冲录入请求
'''
"""CThostFtdcInputOptionSelfCloseField
l_CThostFtdcInputOptionSelfCloseField=py_ApiStructure.InputOptionSelfCloseField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,OptionSelfCloseRef ='?' # ///期权自对冲引用
,UserID ='?' # ///用户代码
,Volume ='?' # ///数量
,RequestID ='?' # ///请求编号
,BusinessUnit ='?' # ///业务单元
,HedgeFlag ='?' # ///投机套保标志
,OptSelfCloseFlag ='?' # ///期权行权的头寸是否自对冲
,ExchangeID ='?' # ///交易所代码
,InvestUnitID ='?' # ///投资单元代码
,AccountID ='?' # ///资金账号
,CurrencyID ='?' # ///币种代码
,ClientID ='?' # ///交易编码
,IPAddress ='?' # ///IP地址
,MacAddress ='?' # ///Mac地址
)
#"""
self.req_call['OptionSelfCloseInsert'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqOptionSelfCloseInsert(pInputOptionSelfClose,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqOptionSelfCloseInsert(pInputOptionSelfClose,self.Inc_RequestID() )
def ReqOptionSelfCloseAction(self, pInputOptionSelfCloseAction):
'''
///期权自对冲操作请求
'''
"""CThostFtdcInputOptionSelfCloseActionField
l_CThostFtdcInputOptionSelfCloseActionField=py_ApiStructure.InputOptionSelfCloseActionField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,OptionSelfCloseActionRef ='?' # ///期权自对冲操作引用
,OptionSelfCloseRef ='?' # ///期权自对冲引用
,RequestID ='?' # ///请求编号
,FrontID ='?' # ///前置编号
,SessionID ='?' # ///会话编号
,ExchangeID ='?' # ///交易所代码
,OptionSelfCloseSysID ='?' # ///期权自对冲操作编号
,ActionFlag ='?' # ///操作标志
,UserID ='?' # ///用户代码
,InstrumentID ='?' # ///合约代码
,InvestUnitID ='?' # ///投资单元代码
,IPAddress ='?' # ///IP地址
,MacAddress ='?' # ///Mac地址
)
#"""
self.req_call['OptionSelfCloseAction'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqOptionSelfCloseAction(pInputOptionSelfCloseAction,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqOptionSelfCloseAction(pInputOptionSelfCloseAction,self.Inc_RequestID() )
def ReqCombActionInsert(self, pInputCombAction):
'''
///申请组合录入请求
'''
"""CThostFtdcInputCombActionField
l_CThostFtdcInputCombActionField=py_ApiStructure.InputCombActionField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,CombActionRef ='?' # ///组合引用
,UserID ='?' # ///用户代码
,Direction ='?' # ///买卖方向
,Volume ='?' # ///数量
,CombDirection ='?' # ///组合指令方向
,HedgeFlag ='?' # ///投机套保标志
,ExchangeID ='?' # ///交易所代码
,IPAddress ='?' # ///IP地址
,MacAddress ='?' # ///Mac地址
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['CombActionInsert'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqCombActionInsert(pInputCombAction,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqCombActionInsert(pInputCombAction,self.Inc_RequestID() )
def ReqQryOrder(self, pQryOrder):
'''
///请求查询报单
'''
"""CThostFtdcQryOrderField
l_CThostFtdcQryOrderField=py_ApiStructure.QryOrderField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,ExchangeID ='?' # ///交易所代码
,OrderSysID ='?' # ///报单编号
,InsertTimeStart ='?' # ///开始时间
,InsertTimeEnd ='?' # ///结束时间
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryOrder'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryOrder(pQryOrder,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryOrder(pQryOrder,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryOrder(it_ret_val, None, nRequestID, True)
return 0
def ReqQryTrade(self, pQryTrade):
'''
///请求查询成交
'''
"""CThostFtdcQryTradeField
l_CThostFtdcQryTradeField=py_ApiStructure.QryTradeField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,ExchangeID ='?' # ///交易所代码
,TradeID ='?' # ///成交编号
,TradeTimeStart ='?' # ///开始时间
,TradeTimeEnd ='?' # ///结束时间
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryTrade'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryTrade(pQryTrade,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryTrade(pQryTrade,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryTrade(it_ret_val, None, nRequestID, True)
return 0
def ReqQryInvestorPosition(self, pQryInvestorPosition):
'''
///请求查询投资者持仓
'''
"""CThostFtdcQryInvestorPositionField
l_CThostFtdcQryInvestorPositionField=py_ApiStructure.QryInvestorPositionField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,ExchangeID ='?' # ///交易所代码
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryInvestorPosition'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryInvestorPosition(pQryInvestorPosition,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryInvestorPosition(pQryInvestorPosition,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryInvestorPosition(it_ret_val, None, nRequestID, True)
return 0
def ReqQryTradingAccount(self, pQryTradingAccount):
'''
///请求查询资金账户
'''
"""CThostFtdcQryTradingAccountField
l_CThostFtdcQryTradingAccountField=py_ApiStructure.QryTradingAccountField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,CurrencyID ='?' # ///币种代码
,BizType ='?' # ///业务类型
,AccountID ='?' # ///投资者帐号
)
#"""
self.req_call['QryTradingAccount'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryTradingAccount(pQryTradingAccount,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryTradingAccount(pQryTradingAccount,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryTradingAccount(it_ret_val, None, nRequestID, True)
return 0
def ReqQryInvestor(self, pQryInvestor):
'''
///请求查询投资者
'''
"""CThostFtdcQryInvestorField
l_CThostFtdcQryInvestorField=py_ApiStructure.QryInvestorField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
)
#"""
self.req_call['QryInvestor'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryInvestor(pQryInvestor,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryInvestor(pQryInvestor,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryInvestor(it_ret_val, None, nRequestID, True)
return 0
def ReqQryTradingCode(self, pQryTradingCode):
'''
///请求查询交易编码
'''
"""CThostFtdcQryTradingCodeField
l_CThostFtdcQryTradingCodeField=py_ApiStructure.QryTradingCodeField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,ExchangeID ='?' # ///交易所代码
,ClientID ='?' # ///客户代码
,ClientIDType ='?' # ///交易编码类型
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryTradingCode'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryTradingCode(pQryTradingCode,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryTradingCode(pQryTradingCode,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryTradingCode(it_ret_val, None, nRequestID, True)
return 0
def ReqQryInstrumentMarginRate(self, pQryInstrumentMarginRate):
'''
///请求查询合约保证金率
'''
"""CThostFtdcQryInstrumentMarginRateField
l_CThostFtdcQryInstrumentMarginRateField=py_ApiStructure.QryInstrumentMarginRateField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,HedgeFlag ='?' # ///投机套保标志
,ExchangeID ='?' # ///交易所代码
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryInstrumentMarginRate'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryInstrumentMarginRate(pQryInstrumentMarginRate,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryInstrumentMarginRate(pQryInstrumentMarginRate,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryInstrumentMarginRate(it_ret_val, None, nRequestID, True)
return 0
def ReqQryInstrumentCommissionRate(self, pQryInstrumentCommissionRate):
'''
///请求查询合约手续费率
'''
"""CThostFtdcQryInstrumentCommissionRateField
l_CThostFtdcQryInstrumentCommissionRateField=py_ApiStructure.QryInstrumentCommissionRateField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,ExchangeID ='?' # ///交易所代码
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryInstrumentCommissionRate'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryInstrumentCommissionRate(pQryInstrumentCommissionRate,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryInstrumentCommissionRate(pQryInstrumentCommissionRate,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryInstrumentCommissionRate(it_ret_val, None, nRequestID, True)
return 0
def ReqQryExchange(self, pQryExchange):
'''
///请求查询交易所
'''
"""CThostFtdcQryExchangeField
l_CThostFtdcQryExchangeField=py_ApiStructure.QryExchangeField(
ExchangeID ='?' # ///交易所代码
)
#"""
self.req_call['QryExchange'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryExchange(pQryExchange,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryExchange(pQryExchange,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryExchange(it_ret_val, None, nRequestID, True)
return 0
def ReqQryProduct(self, pQryProduct):
'''
///请求查询产品
'''
"""CThostFtdcQryProductField
l_CThostFtdcQryProductField=py_ApiStructure.QryProductField(
ProductID ='?' # ///产品代码
,ProductClass ='?' # ///产品类型
,ExchangeID ='?' # ///交易所代码
)
#"""
self.req_call['QryProduct'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryProduct(pQryProduct,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryProduct(pQryProduct,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryProduct(it_ret_val, None, nRequestID, True)
return 0
def ReqQryInstrument(self, pQryInstrument):
'''
///请求查询合约
'''
"""CThostFtdcQryInstrumentField
l_CThostFtdcQryInstrumentField=py_ApiStructure.QryInstrumentField(
InstrumentID ='?' # ///合约代码
,ExchangeID ='?' # ///交易所代码
,ExchangeInstID ='?' # ///合约在交易所的代码
,ProductID ='?' # ///产品代码
)
#"""
self.req_call['QryInstrument'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryInstrument(pQryInstrument,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryInstrument(pQryInstrument,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryInstrument(it_ret_val, None, nRequestID, True)
return 0
def ReqQryDepthMarketData(self, pQryDepthMarketData):
'''
///请求查询行情
'''
"""CThostFtdcQryDepthMarketDataField
l_CThostFtdcQryDepthMarketDataField=py_ApiStructure.QryDepthMarketDataField(
InstrumentID ='?' # ///合约代码
,ExchangeID ='?' # ///交易所代码
)
#"""
self.req_call['QryDepthMarketData'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryDepthMarketData(pQryDepthMarketData,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryDepthMarketData(pQryDepthMarketData,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryDepthMarketData(it_ret_val, None, nRequestID, True)
return 0
def ReqQrySettlementInfo(self, pQrySettlementInfo):
'''
///请求查询投资者结算结果
'''
"""CThostFtdcQrySettlementInfoField
l_CThostFtdcQrySettlementInfoField=py_ApiStructure.QrySettlementInfoField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,TradingDay ='?' # ///交易日
,AccountID ='?' # ///投资者帐号
,CurrencyID ='?' # ///币种代码
)
#"""
self.req_call['QrySettlementInfo'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQrySettlementInfo(pQrySettlementInfo,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQrySettlementInfo(pQrySettlementInfo,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQrySettlementInfo(it_ret_val, None, nRequestID, True)
return 0
def ReqQryTransferBank(self, pQryTransferBank):
'''
///请求查询转帐银行
'''
"""CThostFtdcQryTransferBankField
l_CThostFtdcQryTransferBankField=py_ApiStructure.QryTransferBankField(
BankID ='?' # ///银行代码
,BankBrchID ='?' # ///银行分中心代码
)
#"""
self.req_call['QryTransferBank'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryTransferBank(pQryTransferBank,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryTransferBank(pQryTransferBank,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryTransferBank(it_ret_val, None, nRequestID, True)
return 0
def ReqQryInvestorPositionDetail(self, pQryInvestorPositionDetail):
'''
///请求查询投资者持仓明细
'''
"""CThostFtdcQryInvestorPositionDetailField
l_CThostFtdcQryInvestorPositionDetailField=py_ApiStructure.QryInvestorPositionDetailField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,ExchangeID ='?' # ///交易所代码
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryInvestorPositionDetail'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryInvestorPositionDetail(pQryInvestorPositionDetail,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryInvestorPositionDetail(pQryInvestorPositionDetail,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryInvestorPositionDetail(it_ret_val, None, nRequestID, True)
return 0
def ReqQryNotice(self, pQryNotice):
'''
///请求查询客户通知
'''
"""CThostFtdcQryNoticeField
l_CThostFtdcQryNoticeField=py_ApiStructure.QryNoticeField(
BrokerID ='?' # ///经纪公司代码
)
#"""
self.req_call['QryNotice'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryNotice(pQryNotice,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryNotice(pQryNotice,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryNotice(it_ret_val, None, nRequestID, True)
return 0
def ReqQrySettlementInfoConfirm(self, pQrySettlementInfoConfirm):
'''
///请求查询结算信息确认
'''
"""CThostFtdcQrySettlementInfoConfirmField
l_CThostFtdcQrySettlementInfoConfirmField=py_ApiStructure.QrySettlementInfoConfirmField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,AccountID ='?' # ///投资者帐号
,CurrencyID ='?' # ///币种代码
)
#"""
self.req_call['QrySettlementInfoConfirm'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQrySettlementInfoConfirm(pQrySettlementInfoConfirm,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQrySettlementInfoConfirm(pQrySettlementInfoConfirm,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQrySettlementInfoConfirm(it_ret_val, None, nRequestID, True)
return 0
def ReqQryInvestorPositionCombineDetail(self, pQryInvestorPositionCombineDetail):
'''
///请求查询投资者持仓明细
'''
"""CThostFtdcQryInvestorPositionCombineDetailField
l_CThostFtdcQryInvestorPositionCombineDetailField=py_ApiStructure.QryInvestorPositionCombineDetailField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,CombInstrumentID ='?' # ///组合持仓合约编码
,ExchangeID ='?' # ///交易所代码
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryInvestorPositionCombineDetail'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryInvestorPositionCombineDetail(pQryInvestorPositionCombineDetail,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryInvestorPositionCombineDetail(pQryInvestorPositionCombineDetail,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryInvestorPositionCombineDetail(it_ret_val, None, nRequestID, True)
return 0
def ReqQryCFMMCTradingAccountKey(self, pQryCFMMCTradingAccountKey):
'''
///请求查询保证金监管系统经纪公司资金账户密钥
'''
"""CThostFtdcQryCFMMCTradingAccountKeyField
l_CThostFtdcQryCFMMCTradingAccountKeyField=py_ApiStructure.QryCFMMCTradingAccountKeyField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
)
#"""
self.req_call['QryCFMMCTradingAccountKey'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryCFMMCTradingAccountKey(pQryCFMMCTradingAccountKey,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryCFMMCTradingAccountKey(pQryCFMMCTradingAccountKey,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryCFMMCTradingAccountKey(it_ret_val, None, nRequestID, True)
return 0
def ReqQryEWarrantOffset(self, pQryEWarrantOffset):
'''
///请求查询仓单折抵信息
'''
"""CThostFtdcQryEWarrantOffsetField
l_CThostFtdcQryEWarrantOffsetField=py_ApiStructure.QryEWarrantOffsetField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,ExchangeID ='?' # ///交易所代码
,InstrumentID ='?' # ///合约代码
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryEWarrantOffset'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryEWarrantOffset(pQryEWarrantOffset,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryEWarrantOffset(pQryEWarrantOffset,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryEWarrantOffset(it_ret_val, None, nRequestID, True)
return 0
def ReqQryInvestorProductGroupMargin(self, pQryInvestorProductGroupMargin):
'''
///请求查询投资者品种/跨品种保证金
'''
"""CThostFtdcQryInvestorProductGroupMarginField
l_CThostFtdcQryInvestorProductGroupMarginField=py_ApiStructure.QryInvestorProductGroupMarginField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,ProductGroupID ='?' # ///品种/跨品种标示
,HedgeFlag ='?' # ///投机套保标志
,ExchangeID ='?' # ///交易所代码
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryInvestorProductGroupMargin'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryInvestorProductGroupMargin(pQryInvestorProductGroupMargin,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryInvestorProductGroupMargin(pQryInvestorProductGroupMargin,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryInvestorProductGroupMargin(it_ret_val, None, nRequestID, True)
return 0
def ReqQryExchangeMarginRate(self, pQryExchangeMarginRate):
'''
///请求查询交易所保证金率
'''
"""CThostFtdcQryExchangeMarginRateField
l_CThostFtdcQryExchangeMarginRateField=py_ApiStructure.QryExchangeMarginRateField(
BrokerID ='?' # ///经纪公司代码
,InstrumentID ='?' # ///合约代码
,HedgeFlag ='?' # ///投机套保标志
,ExchangeID ='?' # ///交易所代码
)
#"""
self.req_call['QryExchangeMarginRate'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryExchangeMarginRate(pQryExchangeMarginRate,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryExchangeMarginRate(pQryExchangeMarginRate,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryExchangeMarginRate(it_ret_val, None, nRequestID, True)
return 0
def ReqQryExchangeMarginRateAdjust(self, pQryExchangeMarginRateAdjust):
'''
///请求查询交易所调整保证金率
'''
"""CThostFtdcQryExchangeMarginRateAdjustField
l_CThostFtdcQryExchangeMarginRateAdjustField=py_ApiStructure.QryExchangeMarginRateAdjustField(
BrokerID ='?' # ///经纪公司代码
,InstrumentID ='?' # ///合约代码
,HedgeFlag ='?' # ///投机套保标志
)
#"""
self.req_call['QryExchangeMarginRateAdjust'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryExchangeMarginRateAdjust(pQryExchangeMarginRateAdjust,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryExchangeMarginRateAdjust(pQryExchangeMarginRateAdjust,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryExchangeMarginRateAdjust(it_ret_val, None, nRequestID, True)
return 0
def ReqQryExchangeRate(self, pQryExchangeRate):
'''
///请求查询汇率
'''
"""CThostFtdcQryExchangeRateField
l_CThostFtdcQryExchangeRateField=py_ApiStructure.QryExchangeRateField(
BrokerID ='?' # ///经纪公司代码
,FromCurrencyID ='?' # ///源币种
,ToCurrencyID ='?' # ///目标币种
)
#"""
self.req_call['QryExchangeRate'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryExchangeRate(pQryExchangeRate,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryExchangeRate(pQryExchangeRate,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryExchangeRate(it_ret_val, None, nRequestID, True)
return 0
def ReqQrySecAgentACIDMap(self, pQrySecAgentACIDMap):
'''
///请求查询二级代理操作员银期权限
'''
"""CThostFtdcQrySecAgentACIDMapField
l_CThostFtdcQrySecAgentACIDMapField=py_ApiStructure.QrySecAgentACIDMapField(
BrokerID ='?' # ///经纪公司代码
,UserID ='?' # ///用户代码
,AccountID ='?' # ///资金账户
,CurrencyID ='?' # ///币种
)
#"""
self.req_call['QrySecAgentACIDMap'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQrySecAgentACIDMap(pQrySecAgentACIDMap,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQrySecAgentACIDMap(pQrySecAgentACIDMap,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQrySecAgentACIDMap(it_ret_val, None, nRequestID, True)
return 0
def ReqQryProductExchRate(self, pQryProductExchRate):
'''
///请求查询产品报价汇率
'''
"""CThostFtdcQryProductExchRateField
l_CThostFtdcQryProductExchRateField=py_ApiStructure.QryProductExchRateField(
ProductID ='?' # ///产品代码
,ExchangeID ='?' # ///交易所代码
)
#"""
self.req_call['QryProductExchRate'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryProductExchRate(pQryProductExchRate,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryProductExchRate(pQryProductExchRate,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryProductExchRate(it_ret_val, None, nRequestID, True)
return 0
def ReqQryProductGroup(self, pQryProductGroup):
'''
///请求查询产品组
'''
"""CThostFtdcQryProductGroupField
l_CThostFtdcQryProductGroupField=py_ApiStructure.QryProductGroupField(
ProductID ='?' # ///产品代码
,ExchangeID ='?' # ///交易所代码
)
#"""
self.req_call['QryProductGroup'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryProductGroup(pQryProductGroup,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryProductGroup(pQryProductGroup,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryProductGroup(it_ret_val, None, nRequestID, True)
return 0
def ReqQryMMInstrumentCommissionRate(self, pQryMMInstrumentCommissionRate):
'''
///请求查询做市商合约手续费率
'''
"""CThostFtdcQryMMInstrumentCommissionRateField
l_CThostFtdcQryMMInstrumentCommissionRateField=py_ApiStructure.QryMMInstrumentCommissionRateField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
)
#"""
self.req_call['QryMMInstrumentCommissionRate'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryMMInstrumentCommissionRate(pQryMMInstrumentCommissionRate,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryMMInstrumentCommissionRate(pQryMMInstrumentCommissionRate,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryMMInstrumentCommissionRate(it_ret_val, None, nRequestID, True)
return 0
def ReqQryMMOptionInstrCommRate(self, pQryMMOptionInstrCommRate):
'''
///请求查询做市商期权合约手续费
'''
"""CThostFtdcQryMMOptionInstrCommRateField
l_CThostFtdcQryMMOptionInstrCommRateField=py_ApiStructure.QryMMOptionInstrCommRateField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
)
#"""
self.req_call['QryMMOptionInstrCommRate'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryMMOptionInstrCommRate(pQryMMOptionInstrCommRate,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryMMOptionInstrCommRate(pQryMMOptionInstrCommRate,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryMMOptionInstrCommRate(it_ret_val, None, nRequestID, True)
return 0
def ReqQryInstrumentOrderCommRate(self, pQryInstrumentOrderCommRate):
'''
///请求查询报单手续费
'''
"""CThostFtdcQryInstrumentOrderCommRateField
l_CThostFtdcQryInstrumentOrderCommRateField=py_ApiStructure.QryInstrumentOrderCommRateField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
)
#"""
self.req_call['QryInstrumentOrderCommRate'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryInstrumentOrderCommRate(pQryInstrumentOrderCommRate,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryInstrumentOrderCommRate(pQryInstrumentOrderCommRate,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryInstrumentOrderCommRate(it_ret_val, None, nRequestID, True)
return 0
def ReqQrySecAgentTradingAccount(self, pQryTradingAccount):
'''
///请求查询资金账户
'''
"""CThostFtdcQryTradingAccountField
l_CThostFtdcQryTradingAccountField=py_ApiStructure.QryTradingAccountField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,CurrencyID ='?' # ///币种代码
,BizType ='?' # ///业务类型
,AccountID ='?' # ///投资者帐号
)
#"""
self.req_call['QrySecAgentTradingAccount'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQrySecAgentTradingAccount(pQryTradingAccount,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQrySecAgentTradingAccount(pQryTradingAccount,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQrySecAgentTradingAccount(it_ret_val, None, nRequestID, True)
return 0
def ReqQrySecAgentCheckMode(self, pQrySecAgentCheckMode):
'''
///请求查询二级代理商资金校验模式
'''
"""CThostFtdcQrySecAgentCheckModeField
l_CThostFtdcQrySecAgentCheckModeField=py_ApiStructure.QrySecAgentCheckModeField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
)
#"""
self.req_call['QrySecAgentCheckMode'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQrySecAgentCheckMode(pQrySecAgentCheckMode,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQrySecAgentCheckMode(pQrySecAgentCheckMode,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQrySecAgentCheckMode(it_ret_val, None, nRequestID, True)
return 0
def ReqQryOptionInstrTradeCost(self, pQryOptionInstrTradeCost):
'''
///请求查询期权交易成本
'''
"""CThostFtdcQryOptionInstrTradeCostField
l_CThostFtdcQryOptionInstrTradeCostField=py_ApiStructure.QryOptionInstrTradeCostField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,HedgeFlag ='?' # ///投机套保标志
,InputPrice ='?' # ///期权合约报价
,UnderlyingPrice ='?' # ///标的价格,填0则用昨结算价
,ExchangeID ='?' # ///交易所代码
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryOptionInstrTradeCost'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryOptionInstrTradeCost(pQryOptionInstrTradeCost,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryOptionInstrTradeCost(pQryOptionInstrTradeCost,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryOptionInstrTradeCost(it_ret_val, None, nRequestID, True)
return 0
def ReqQryOptionInstrCommRate(self, pQryOptionInstrCommRate):
'''
///请求查询期权合约手续费
'''
"""CThostFtdcQryOptionInstrCommRateField
l_CThostFtdcQryOptionInstrCommRateField=py_ApiStructure.QryOptionInstrCommRateField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,ExchangeID ='?' # ///交易所代码
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryOptionInstrCommRate'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryOptionInstrCommRate(pQryOptionInstrCommRate,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryOptionInstrCommRate(pQryOptionInstrCommRate,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryOptionInstrCommRate(it_ret_val, None, nRequestID, True)
return 0
def ReqQryExecOrder(self, pQryExecOrder):
'''
///请求查询执行宣告
'''
"""CThostFtdcQryExecOrderField
l_CThostFtdcQryExecOrderField=py_ApiStructure.QryExecOrderField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,ExchangeID ='?' # ///交易所代码
,ExecOrderSysID ='?' # ///执行宣告编号
,InsertTimeStart ='?' # ///开始时间
,InsertTimeEnd ='?' # ///结束时间
)
#"""
self.req_call['QryExecOrder'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryExecOrder(pQryExecOrder,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryExecOrder(pQryExecOrder,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryExecOrder(it_ret_val, None, nRequestID, True)
return 0
def ReqQryForQuote(self, pQryForQuote):
'''
///请求查询询价
'''
"""CThostFtdcQryForQuoteField
l_CThostFtdcQryForQuoteField=py_ApiStructure.QryForQuoteField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,ExchangeID ='?' # ///交易所代码
,InsertTimeStart ='?' # ///开始时间
,InsertTimeEnd ='?' # ///结束时间
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryForQuote'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryForQuote(pQryForQuote,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryForQuote(pQryForQuote,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryForQuote(it_ret_val, None, nRequestID, True)
return 0
def ReqQryQuote(self, pQryQuote):
'''
///请求查询报价
'''
"""CThostFtdcQryQuoteField
l_CThostFtdcQryQuoteField=py_ApiStructure.QryQuoteField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,ExchangeID ='?' # ///交易所代码
,QuoteSysID ='?' # ///报价编号
,InsertTimeStart ='?' # ///开始时间
,InsertTimeEnd ='?' # ///结束时间
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryQuote'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryQuote(pQryQuote,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryQuote(pQryQuote,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryQuote(it_ret_val, None, nRequestID, True)
return 0
def ReqQryOptionSelfClose(self, pQryOptionSelfClose):
'''
///请求查询期权自对冲
'''
"""CThostFtdcQryOptionSelfCloseField
l_CThostFtdcQryOptionSelfCloseField=py_ApiStructure.QryOptionSelfCloseField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,ExchangeID ='?' # ///交易所代码
,OptionSelfCloseSysID ='?' # ///期权自对冲编号
,InsertTimeStart ='?' # ///开始时间
,InsertTimeEnd ='?' # ///结束时间
)
#"""
self.req_call['QryOptionSelfClose'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryOptionSelfClose(pQryOptionSelfClose,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryOptionSelfClose(pQryOptionSelfClose,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryOptionSelfClose(it_ret_val, None, nRequestID, True)
return 0
def ReqQryInvestUnit(self, pQryInvestUnit):
'''
///请求查询投资单元
'''
"""CThostFtdcQryInvestUnitField
l_CThostFtdcQryInvestUnitField=py_ApiStructure.QryInvestUnitField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryInvestUnit'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryInvestUnit(pQryInvestUnit,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryInvestUnit(pQryInvestUnit,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryInvestUnit(it_ret_val, None, nRequestID, True)
return 0
def ReqQryCombInstrumentGuard(self, pQryCombInstrumentGuard):
'''
///请求查询组合合约安全系数
'''
"""CThostFtdcQryCombInstrumentGuardField
l_CThostFtdcQryCombInstrumentGuardField=py_ApiStructure.QryCombInstrumentGuardField(
BrokerID ='?' # ///经纪公司代码
,InstrumentID ='?' # ///合约代码
,ExchangeID ='?' # ///交易所代码
)
#"""
self.req_call['QryCombInstrumentGuard'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryCombInstrumentGuard(pQryCombInstrumentGuard,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryCombInstrumentGuard(pQryCombInstrumentGuard,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryCombInstrumentGuard(it_ret_val, None, nRequestID, True)
return 0
def ReqQryCombAction(self, pQryCombAction):
'''
///请求查询申请组合
'''
"""CThostFtdcQryCombActionField
l_CThostFtdcQryCombActionField=py_ApiStructure.QryCombActionField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,ExchangeID ='?' # ///交易所代码
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryCombAction'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryCombAction(pQryCombAction,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryCombAction(pQryCombAction,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryCombAction(it_ret_val, None, nRequestID, True)
return 0
def ReqQryTransferSerial(self, pQryTransferSerial):
'''
///请求查询转帐流水
'''
"""CThostFtdcQryTransferSerialField
l_CThostFtdcQryTransferSerialField=py_ApiStructure.QryTransferSerialField(
BrokerID ='?' # ///经纪公司代码
,AccountID ='?' # ///投资者帐号
,BankID ='?' # ///银行编码
,CurrencyID ='?' # ///币种代码
)
#"""
self.req_call['QryTransferSerial'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryTransferSerial(pQryTransferSerial,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryTransferSerial(pQryTransferSerial,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryTransferSerial(it_ret_val, None, nRequestID, True)
return 0
def ReqQryAccountregister(self, pQryAccountregister):
'''
///请求查询银期签约关系
'''
"""CThostFtdcQryAccountregisterField
l_CThostFtdcQryAccountregisterField=py_ApiStructure.QryAccountregisterField(
BrokerID ='?' # ///经纪公司代码
,AccountID ='?' # ///投资者帐号
,BankID ='?' # ///银行编码
,BankBranchID ='?' # ///银行分支机构编码
,CurrencyID ='?' # ///币种代码
)
#"""
self.req_call['QryAccountregister'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryAccountregister(pQryAccountregister,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryAccountregister(pQryAccountregister,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryAccountregister(it_ret_val, None, nRequestID, True)
return 0
def ReqQryContractBank(self, pQryContractBank):
'''
///请求查询签约银行
'''
"""CThostFtdcQryContractBankField
l_CThostFtdcQryContractBankField=py_ApiStructure.QryContractBankField(
BrokerID ='?' # ///经纪公司代码
,BankID ='?' # ///银行代码
,BankBrchID ='?' # ///银行分中心代码
)
#"""
self.req_call['QryContractBank'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryContractBank(pQryContractBank,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryContractBank(pQryContractBank,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryContractBank(it_ret_val, None, nRequestID, True)
return 0
def ReqQryParkedOrder(self, pQryParkedOrder):
'''
///请求查询预埋单
'''
"""CThostFtdcQryParkedOrderField
l_CThostFtdcQryParkedOrderField=py_ApiStructure.QryParkedOrderField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,ExchangeID ='?' # ///交易所代码
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryParkedOrder'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryParkedOrder(pQryParkedOrder,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryParkedOrder(pQryParkedOrder,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryParkedOrder(it_ret_val, None, nRequestID, True)
return 0
def ReqQryParkedOrderAction(self, pQryParkedOrderAction):
'''
///请求查询预埋撤单
'''
"""CThostFtdcQryParkedOrderActionField
l_CThostFtdcQryParkedOrderActionField=py_ApiStructure.QryParkedOrderActionField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InstrumentID ='?' # ///合约代码
,ExchangeID ='?' # ///交易所代码
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryParkedOrderAction'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryParkedOrderAction(pQryParkedOrderAction,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryParkedOrderAction(pQryParkedOrderAction,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryParkedOrderAction(it_ret_val, None, nRequestID, True)
return 0
def ReqQryTradingNotice(self, pQryTradingNotice):
'''
///请求查询交易通知
'''
"""CThostFtdcQryTradingNoticeField
l_CThostFtdcQryTradingNoticeField=py_ApiStructure.QryTradingNoticeField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QryTradingNotice'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryTradingNotice(pQryTradingNotice,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryTradingNotice(pQryTradingNotice,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryTradingNotice(it_ret_val, None, nRequestID, True)
return 0
def ReqQryBrokerTradingParams(self, pQryBrokerTradingParams):
'''
///请求查询经纪公司交易参数
'''
"""CThostFtdcQryBrokerTradingParamsField
l_CThostFtdcQryBrokerTradingParamsField=py_ApiStructure.QryBrokerTradingParamsField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,CurrencyID ='?' # ///币种代码
,AccountID ='?' # ///投资者帐号
)
#"""
self.req_call['QryBrokerTradingParams'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryBrokerTradingParams(pQryBrokerTradingParams,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryBrokerTradingParams(pQryBrokerTradingParams,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryBrokerTradingParams(it_ret_val, None, nRequestID, True)
return 0
def ReqQryBrokerTradingAlgos(self, pQryBrokerTradingAlgos):
'''
///请求查询经纪公司交易算法
'''
"""CThostFtdcQryBrokerTradingAlgosField
l_CThostFtdcQryBrokerTradingAlgosField=py_ApiStructure.QryBrokerTradingAlgosField(
BrokerID ='?' # ///经纪公司代码
,ExchangeID ='?' # ///交易所代码
,InstrumentID ='?' # ///合约代码
)
#"""
self.req_call['QryBrokerTradingAlgos'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQryBrokerTradingAlgos(pQryBrokerTradingAlgos,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQryBrokerTradingAlgos(pQryBrokerTradingAlgos,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQryBrokerTradingAlgos(it_ret_val, None, nRequestID, True)
return 0
def ReqQueryCFMMCTradingAccountToken(self, pQueryCFMMCTradingAccountToken):
'''
///请求查询监控中心用户令牌
'''
"""CThostFtdcQueryCFMMCTradingAccountTokenField
l_CThostFtdcQueryCFMMCTradingAccountTokenField=py_ApiStructure.QueryCFMMCTradingAccountTokenField(
BrokerID ='?' # ///经纪公司代码
,InvestorID ='?' # ///投资者代码
,InvestUnitID ='?' # ///投资单元代码
)
#"""
self.req_call['QueryCFMMCTradingAccountToken'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQueryCFMMCTradingAccountToken(pQueryCFMMCTradingAccountToken,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQueryCFMMCTradingAccountToken(pQueryCFMMCTradingAccountToken,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQueryCFMMCTradingAccountToken(it_ret_val, None, nRequestID, True)
return 0
def ReqFromBankToFutureByFuture(self, pReqTransfer):
'''
///期货发起银行资金转期货请求
'''
"""CThostFtdcReqTransferField
l_CThostFtdcReqTransferField=py_ApiStructure.ReqTransferField(
TradeCode ='?' # ///业务功能码
,BankID ='?' # ///银行代码
,BankBranchID ='?' # ///银行分支机构代码
,BrokerID ='?' # ///期商代码
,BrokerBranchID ='?' # ///期商分支机构代码
,TradeDate ='?' # ///交易日期
,TradeTime ='?' # ///交易时间
,BankSerial ='?' # ///银行流水号
,TradingDay ='?' # ///交易系统日期
,PlateSerial ='?' # ///银期平台消息流水号
,LastFragment ='?' # ///最后分片标志
,SessionID ='?' # ///会话号
,CustomerName ='?' # ///客户姓名
,IdCardType ='?' # ///证件类型
,IdentifiedCardNo ='?' # ///证件号码
,CustType ='?' # ///客户类型
,BankAccount ='?' # ///银行帐号
,BankPassWord ='?' # ///银行密码
,AccountID ='?' # ///投资者帐号
,Password ='?' # ///期货密码
,InstallID ='?' # ///安装编号
,FutureSerial ='?' # ///期货公司流水号
,UserID ='?' # ///用户标识
,VerifyCertNoFlag ='?' # ///验证客户证件号码标志
,CurrencyID ='?' # ///币种代码
,TradeAmount ='?' # ///转帐金额
,FutureFetchAmount ='?' # ///期货可取金额
,FeePayFlag ='?' # ///费用支付标志
,CustFee ='?' # ///应收客户费用
,BrokerFee ='?' # ///应收期货公司费用
,Message ='?' # ///发送方给接收方的消息
,Digest ='?' # ///摘要
,BankAccType ='?' # ///银行帐号类型
,DeviceID ='?' # ///渠道标志
,BankSecuAccType ='?' # ///期货单位帐号类型
,BrokerIDByBank ='?' # ///期货公司银行编码
,BankSecuAcc ='?' # ///期货单位帐号
,BankPwdFlag ='?' # ///银行密码标志
,SecuPwdFlag ='?' # ///期货资金密码核对标志
,OperNo ='?' # ///交易柜员
,RequestID ='?' # ///请求编号
,TID ='?' # ///交易ID
,TransferStatus ='?' # ///转账交易状态
,LongCustomerName ='?' # ///长客户姓名
)
#"""
self.req_call['FromBankToFutureByFuture'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqFromBankToFutureByFuture(pReqTransfer,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqFromBankToFutureByFuture(pReqTransfer,self.Inc_RequestID() )
def ReqFromFutureToBankByFuture(self, pReqTransfer):
'''
///期货发起期货资金转银行请求
'''
"""CThostFtdcReqTransferField
l_CThostFtdcReqTransferField=py_ApiStructure.ReqTransferField(
TradeCode ='?' # ///业务功能码
,BankID ='?' # ///银行代码
,BankBranchID ='?' # ///银行分支机构代码
,BrokerID ='?' # ///期商代码
,BrokerBranchID ='?' # ///期商分支机构代码
,TradeDate ='?' # ///交易日期
,TradeTime ='?' # ///交易时间
,BankSerial ='?' # ///银行流水号
,TradingDay ='?' # ///交易系统日期
,PlateSerial ='?' # ///银期平台消息流水号
,LastFragment ='?' # ///最后分片标志
,SessionID ='?' # ///会话号
,CustomerName ='?' # ///客户姓名
,IdCardType ='?' # ///证件类型
,IdentifiedCardNo ='?' # ///证件号码
,CustType ='?' # ///客户类型
,BankAccount ='?' # ///银行帐号
,BankPassWord ='?' # ///银行密码
,AccountID ='?' # ///投资者帐号
,Password ='?' # ///期货密码
,InstallID ='?' # ///安装编号
,FutureSerial ='?' # ///期货公司流水号
,UserID ='?' # ///用户标识
,VerifyCertNoFlag ='?' # ///验证客户证件号码标志
,CurrencyID ='?' # ///币种代码
,TradeAmount ='?' # ///转帐金额
,FutureFetchAmount ='?' # ///期货可取金额
,FeePayFlag ='?' # ///费用支付标志
,CustFee ='?' # ///应收客户费用
,BrokerFee ='?' # ///应收期货公司费用
,Message ='?' # ///发送方给接收方的消息
,Digest ='?' # ///摘要
,BankAccType ='?' # ///银行帐号类型
,DeviceID ='?' # ///渠道标志
,BankSecuAccType ='?' # ///期货单位帐号类型
,BrokerIDByBank ='?' # ///期货公司银行编码
,BankSecuAcc ='?' # ///期货单位帐号
,BankPwdFlag ='?' # ///银行密码标志
,SecuPwdFlag ='?' # ///期货资金密码核对标志
,OperNo ='?' # ///交易柜员
,RequestID ='?' # ///请求编号
,TID ='?' # ///交易ID
,TransferStatus ='?' # ///转账交易状态
,LongCustomerName ='?' # ///长客户姓名
)
#"""
self.req_call['FromFutureToBankByFuture'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqFromFutureToBankByFuture(pReqTransfer,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqFromFutureToBankByFuture(pReqTransfer,self.Inc_RequestID() )
def ReqQueryBankAccountMoneyByFuture(self, pReqQueryAccount):
'''
///期货发起查询银行余额请求
'''
"""CThostFtdcReqQueryAccountField
l_CThostFtdcReqQueryAccountField=py_ApiStructure.ReqQueryAccountField(
TradeCode ='?' # ///业务功能码
,BankID ='?' # ///银行代码
,BankBranchID ='?' # ///银行分支机构代码
,BrokerID ='?' # ///期商代码
,BrokerBranchID ='?' # ///期商分支机构代码
,TradeDate ='?' # ///交易日期
,TradeTime ='?' # ///交易时间
,BankSerial ='?' # ///银行流水号
,TradingDay ='?' # ///交易系统日期
,PlateSerial ='?' # ///银期平台消息流水号
,LastFragment ='?' # ///最后分片标志
,SessionID ='?' # ///会话号
,CustomerName ='?' # ///客户姓名
,IdCardType ='?' # ///证件类型
,IdentifiedCardNo ='?' # ///证件号码
,CustType ='?' # ///客户类型
,BankAccount ='?' # ///银行帐号
,BankPassWord ='?' # ///银行密码
,AccountID ='?' # ///投资者帐号
,Password ='?' # ///期货密码
,FutureSerial ='?' # ///期货公司流水号
,InstallID ='?' # ///安装编号
,UserID ='?' # ///用户标识
,VerifyCertNoFlag ='?' # ///验证客户证件号码标志
,CurrencyID ='?' # ///币种代码
,Digest ='?' # ///摘要
,BankAccType ='?' # ///银行帐号类型
,DeviceID ='?' # ///渠道标志
,BankSecuAccType ='?' # ///期货单位帐号类型
,BrokerIDByBank ='?' # ///期货公司银行编码
,BankSecuAcc ='?' # ///期货单位帐号
,BankPwdFlag ='?' # ///银行密码标志
,SecuPwdFlag ='?' # ///期货资金密码核对标志
,OperNo ='?' # ///交易柜员
,RequestID ='?' # ///请求编号
,TID ='?' # ///交易ID
,LongCustomerName ='?' # ///长客户姓名
)
#"""
self.req_call['QueryBankAccountMoneyByFuture'] = 0
if self.Trader_Rule == 0:
return super(py_CtpTrader, self).ReqQueryBankAccountMoneyByFuture(pReqQueryAccount,self.Inc_RequestID() )
else:
nRequestID = self.Inc_RequestID()
ret_val_list = self.PTP_Algos.ReqQueryBankAccountMoneyByFuture(pReqQueryAccount,nRequestID )
for it_ret_val in ret_val_list:
self.OnRspQueryBankAccountMoneyByFuture(it_ret_val, None, nRequestID, True)
return 0
def OnRspAuthenticate(self, pRspAuthenticateField, pRspInfo, nRequestID, bIsLast):
'''
///客户端认证响应
'''
if bIsLast == True:
self.req_call['Authenticate'] = 1
self.PTP_Algos.DumpRspDict("T_RspAuthenticate",pRspAuthenticate)
l_dict={}
"""CThostFtdcRspAuthenticateField
# ///经纪公司代码
l_dict["BrokerID"] = pRspAuthenticate.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pRspAuthenticate.UserID.decode(encoding="gb18030", errors="ignore")
# ///用户端产品信息
l_dict["UserProductInfo"] = pRspAuthenticate.UserProductInfo.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspUserLogout(self, pUserLogout, pRspInfo, nRequestID, bIsLast):
'''
///登出请求响应
'''
if bIsLast == True:
self.req_call['UserLogout'] = 1
self.PTP_Algos.DumpRspDict("T_UserLogout",pUserLogout)
l_dict={}
"""CThostFtdcUserLogoutField
# ///经纪公司代码
l_dict["BrokerID"] = pUserLogout.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pUserLogout.UserID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspUserPasswordUpdate(self, pUserPasswordUpdate, pRspInfo, nRequestID, bIsLast):
'''
///用户口令更新请求响应
'''
if bIsLast == True:
self.req_call['UserPasswordUpdate'] = 1
self.PTP_Algos.DumpRspDict("T_UserPasswordUpdate",pUserPasswordUpdate)
l_dict={}
"""CThostFtdcUserPasswordUpdateField
# ///经纪公司代码
l_dict["BrokerID"] = pUserPasswordUpdate.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pUserPasswordUpdate.UserID.decode(encoding="gb18030", errors="ignore")
# ///原来的口令
l_dict["OldPassword"] = pUserPasswordUpdate.OldPassword.decode(encoding="gb18030", errors="ignore")
# ///新的口令
l_dict["NewPassword"] = pUserPasswordUpdate.NewPassword.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspTradingAccountPasswordUpdate(self, pTradingAccountPasswordUpdate, pRspInfo, nRequestID, bIsLast):
'''
///资金账户口令更新请求响应
'''
if bIsLast == True:
self.req_call['TradingAccountPasswordUpdate'] = 1
self.PTP_Algos.DumpRspDict("T_TradingAccountPasswordUpdate",pTradingAccountPasswordUpdate)
l_dict={}
"""CThostFtdcTradingAccountPasswordUpdateField
# ///经纪公司代码
l_dict["BrokerID"] = pTradingAccountPasswordUpdate.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pTradingAccountPasswordUpdate.AccountID.decode(encoding="gb18030", errors="ignore")
# ///原来的口令
l_dict["OldPassword"] = pTradingAccountPasswordUpdate.OldPassword.decode(encoding="gb18030", errors="ignore")
# ///新的口令
l_dict["NewPassword"] = pTradingAccountPasswordUpdate.NewPassword.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pTradingAccountPasswordUpdate.CurrencyID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspOrderInsert(self, pInputOrder, pRspInfo, nRequestID, bIsLast):
'''
///报单录入请求响应
'''
if bIsLast == True:
self.req_call['OrderInsert'] = 1
self.PTP_Algos.push_OnRspOrderInsert("T_InputOrder",pInputOrder)
l_dict={}
"""CThostFtdcInputOrderField
# ///经纪公司代码
l_dict["BrokerID"] = pInputOrder.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInputOrder.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pInputOrder.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///报单引用
l_dict["OrderRef"] = pInputOrder.OrderRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pInputOrder.UserID.decode(encoding="gb18030", errors="ignore")
# ///报单价格条件
l_dict["OrderPriceType"] = pInputOrder.OrderPriceType.decode(encoding="gb18030", errors="ignore")
# ///买卖方向
l_dict["Direction"] = pInputOrder.Direction.decode(encoding="gb18030", errors="ignore")
# ///组合开平标志
l_dict["CombOffsetFlag"] = pInputOrder.CombOffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///组合投机套保标志
l_dict["CombHedgeFlag"] = pInputOrder.CombHedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///价格
l_dict["LimitPrice"] = pInputOrder.LimitPrice
# ///数量
l_dict["VolumeTotalOriginal"] = pInputOrder.VolumeTotalOriginal
# ///有效期类型
l_dict["TimeCondition"] = pInputOrder.TimeCondition.decode(encoding="gb18030", errors="ignore")
# ///GTD日期
l_dict["GTDDate"] = pInputOrder.GTDDate.decode(encoding="gb18030", errors="ignore")
# ///成交量类型
l_dict["VolumeCondition"] = pInputOrder.VolumeCondition.decode(encoding="gb18030", errors="ignore")
# ///最小成交量
l_dict["MinVolume"] = pInputOrder.MinVolume
# ///触发条件
l_dict["ContingentCondition"] = pInputOrder.ContingentCondition.decode(encoding="gb18030", errors="ignore")
# ///止损价
l_dict["StopPrice"] = pInputOrder.StopPrice
# ///强平原因
l_dict["ForceCloseReason"] = pInputOrder.ForceCloseReason.decode(encoding="gb18030", errors="ignore")
# ///自动挂起标志
l_dict["IsAutoSuspend"] = pInputOrder.IsAutoSuspend
# ///业务单元
l_dict["BusinessUnit"] = pInputOrder.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pInputOrder.RequestID
# ///用户强评标志
l_dict["UserForceClose"] = pInputOrder.UserForceClose
# ///互换单标志
l_dict["IsSwapOrder"] = pInputOrder.IsSwapOrder
# ///交易所代码
l_dict["ExchangeID"] = pInputOrder.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInputOrder.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///资金账号
l_dict["AccountID"] = pInputOrder.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pInputOrder.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///交易编码
l_dict["ClientID"] = pInputOrder.ClientID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pInputOrder.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pInputOrder.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspParkedOrderInsert(self, pParkedOrder, pRspInfo, nRequestID, bIsLast):
'''
///预埋单录入请求响应
'''
if bIsLast == True:
self.req_call['ParkedOrderInsert'] = 1
self.PTP_Algos.DumpRspDict("T_ParkedOrder",pParkedOrder)
l_dict={}
"""CThostFtdcParkedOrderField
# ///经纪公司代码
l_dict["BrokerID"] = pParkedOrder.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pParkedOrder.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pParkedOrder.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///报单引用
l_dict["OrderRef"] = pParkedOrder.OrderRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pParkedOrder.UserID.decode(encoding="gb18030", errors="ignore")
# ///报单价格条件
l_dict["OrderPriceType"] = pParkedOrder.OrderPriceType.decode(encoding="gb18030", errors="ignore")
# ///买卖方向
l_dict["Direction"] = pParkedOrder.Direction.decode(encoding="gb18030", errors="ignore")
# ///组合开平标志
l_dict["CombOffsetFlag"] = pParkedOrder.CombOffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///组合投机套保标志
l_dict["CombHedgeFlag"] = pParkedOrder.CombHedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///价格
l_dict["LimitPrice"] = pParkedOrder.LimitPrice
# ///数量
l_dict["VolumeTotalOriginal"] = pParkedOrder.VolumeTotalOriginal
# ///有效期类型
l_dict["TimeCondition"] = pParkedOrder.TimeCondition.decode(encoding="gb18030", errors="ignore")
# ///GTD日期
l_dict["GTDDate"] = pParkedOrder.GTDDate.decode(encoding="gb18030", errors="ignore")
# ///成交量类型
l_dict["VolumeCondition"] = pParkedOrder.VolumeCondition.decode(encoding="gb18030", errors="ignore")
# ///最小成交量
l_dict["MinVolume"] = pParkedOrder.MinVolume
# ///触发条件
l_dict["ContingentCondition"] = pParkedOrder.ContingentCondition.decode(encoding="gb18030", errors="ignore")
# ///止损价
l_dict["StopPrice"] = pParkedOrder.StopPrice
# ///强平原因
l_dict["ForceCloseReason"] = pParkedOrder.ForceCloseReason.decode(encoding="gb18030", errors="ignore")
# ///自动挂起标志
l_dict["IsAutoSuspend"] = pParkedOrder.IsAutoSuspend
# ///业务单元
l_dict["BusinessUnit"] = pParkedOrder.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pParkedOrder.RequestID
# ///用户强评标志
l_dict["UserForceClose"] = pParkedOrder.UserForceClose
# ///交易所代码
l_dict["ExchangeID"] = pParkedOrder.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///预埋报单编号
l_dict["ParkedOrderID"] = pParkedOrder.ParkedOrderID.decode(encoding="gb18030", errors="ignore")
# ///用户类型
l_dict["UserType"] = pParkedOrder.UserType.decode(encoding="gb18030", errors="ignore")
# ///预埋单状态
l_dict["Status"] = pParkedOrder.Status.decode(encoding="gb18030", errors="ignore")
# ///错误代码
l_dict["ErrorID"] = pParkedOrder.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pParkedOrder.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///互换单标志
l_dict["IsSwapOrder"] = pParkedOrder.IsSwapOrder
# ///资金账号
l_dict["AccountID"] = pParkedOrder.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pParkedOrder.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///交易编码
l_dict["ClientID"] = pParkedOrder.ClientID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pParkedOrder.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pParkedOrder.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pParkedOrder.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspParkedOrderAction(self, pParkedOrderAction, pRspInfo, nRequestID, bIsLast):
'''
///预埋撤单录入请求响应
'''
if bIsLast == True:
self.req_call['ParkedOrderAction'] = 1
self.PTP_Algos.DumpRspDict("T_ParkedOrderAction",pParkedOrderAction)
l_dict={}
"""CThostFtdcParkedOrderActionField
# ///经纪公司代码
l_dict["BrokerID"] = pParkedOrderAction.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pParkedOrderAction.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///报单操作引用
l_dict["OrderActionRef"] = pParkedOrderAction.OrderActionRef
# ///报单引用
l_dict["OrderRef"] = pParkedOrderAction.OrderRef.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pParkedOrderAction.RequestID
# ///前置编号
l_dict["FrontID"] = pParkedOrderAction.FrontID
# ///会话编号
l_dict["SessionID"] = pParkedOrderAction.SessionID
# ///交易所代码
l_dict["ExchangeID"] = pParkedOrderAction.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///报单编号
l_dict["OrderSysID"] = pParkedOrderAction.OrderSysID.decode(encoding="gb18030", errors="ignore")
# ///操作标志
l_dict["ActionFlag"] = pParkedOrderAction.ActionFlag.decode(encoding="gb18030", errors="ignore")
# ///价格
l_dict["LimitPrice"] = pParkedOrderAction.LimitPrice
# ///数量变化
l_dict["VolumeChange"] = pParkedOrderAction.VolumeChange
# ///用户代码
l_dict["UserID"] = pParkedOrderAction.UserID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pParkedOrderAction.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///预埋撤单单编号
l_dict["ParkedOrderActionID"] = pParkedOrderAction.ParkedOrderActionID.decode(encoding="gb18030", errors="ignore")
# ///用户类型
l_dict["UserType"] = pParkedOrderAction.UserType.decode(encoding="gb18030", errors="ignore")
# ///预埋撤单状态
l_dict["Status"] = pParkedOrderAction.Status.decode(encoding="gb18030", errors="ignore")
# ///错误代码
l_dict["ErrorID"] = pParkedOrderAction.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pParkedOrderAction.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pParkedOrderAction.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pParkedOrderAction.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pParkedOrderAction.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspOrderAction(self, pInputOrderAction, pRspInfo, nRequestID, bIsLast):
'''
///报单操作请求响应
'''
if bIsLast == True:
self.req_call['OrderAction'] = 1
self.PTP_Algos.DumpRspDict("T_InputOrderAction",pInputOrderAction)
l_dict={}
"""CThostFtdcInputOrderActionField
# ///经纪公司代码
l_dict["BrokerID"] = pInputOrderAction.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInputOrderAction.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///报单操作引用
l_dict["OrderActionRef"] = pInputOrderAction.OrderActionRef
# ///报单引用
l_dict["OrderRef"] = pInputOrderAction.OrderRef.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pInputOrderAction.RequestID
# ///前置编号
l_dict["FrontID"] = pInputOrderAction.FrontID
# ///会话编号
l_dict["SessionID"] = pInputOrderAction.SessionID
# ///交易所代码
l_dict["ExchangeID"] = pInputOrderAction.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///报单编号
l_dict["OrderSysID"] = pInputOrderAction.OrderSysID.decode(encoding="gb18030", errors="ignore")
# ///操作标志
l_dict["ActionFlag"] = pInputOrderAction.ActionFlag.decode(encoding="gb18030", errors="ignore")
# ///价格
l_dict["LimitPrice"] = pInputOrderAction.LimitPrice
# ///数量变化
l_dict["VolumeChange"] = pInputOrderAction.VolumeChange
# ///用户代码
l_dict["UserID"] = pInputOrderAction.UserID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pInputOrderAction.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInputOrderAction.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pInputOrderAction.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pInputOrderAction.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQueryMaxOrderVolume(self, pQueryMaxOrderVolume, pRspInfo, nRequestID, bIsLast):
'''
///查询最大报单数量响应
'''
if bIsLast == True:
self.req_call['QueryMaxOrderVolume'] = 1
self.PTP_Algos.DumpRspDict("T_QueryMaxOrderVolume",pQueryMaxOrderVolume)
l_dict={}
"""CThostFtdcQueryMaxOrderVolumeField
# ///经纪公司代码
l_dict["BrokerID"] = pQueryMaxOrderVolume.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pQueryMaxOrderVolume.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pQueryMaxOrderVolume.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///买卖方向
l_dict["Direction"] = pQueryMaxOrderVolume.Direction.decode(encoding="gb18030", errors="ignore")
# ///开平标志
l_dict["OffsetFlag"] = pQueryMaxOrderVolume.OffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pQueryMaxOrderVolume.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///最大允许报单数量
l_dict["MaxVolume"] = pQueryMaxOrderVolume.MaxVolume
# ///交易所代码
l_dict["ExchangeID"] = pQueryMaxOrderVolume.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pQueryMaxOrderVolume.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspSettlementInfoConfirm(self, pSettlementInfoConfirm, pRspInfo, nRequestID, bIsLast):
'''
///投资者结算结果确认响应
'''
if bIsLast == True:
self.req_call['SettlementInfoConfirm'] = 1
self.PTP_Algos.DumpRspDict("T_SettlementInfoConfirm",pSettlementInfoConfirm)
l_dict={}
"""CThostFtdcSettlementInfoConfirmField
# ///经纪公司代码
l_dict["BrokerID"] = pSettlementInfoConfirm.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pSettlementInfoConfirm.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///确认日期
l_dict["ConfirmDate"] = pSettlementInfoConfirm.ConfirmDate.decode(encoding="gb18030", errors="ignore")
# ///确认时间
l_dict["ConfirmTime"] = pSettlementInfoConfirm.ConfirmTime.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pSettlementInfoConfirm.SettlementID
# ///投资者帐号
l_dict["AccountID"] = pSettlementInfoConfirm.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pSettlementInfoConfirm.CurrencyID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspRemoveParkedOrder(self, pRemoveParkedOrder, pRspInfo, nRequestID, bIsLast):
'''
///删除预埋单响应
'''
if bIsLast == True:
self.req_call['RemoveParkedOrder'] = 1
self.PTP_Algos.DumpRspDict("T_RemoveParkedOrder",pRemoveParkedOrder)
l_dict={}
"""CThostFtdcRemoveParkedOrderField
# ///经纪公司代码
l_dict["BrokerID"] = pRemoveParkedOrder.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pRemoveParkedOrder.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///预埋报单编号
l_dict["ParkedOrderID"] = pRemoveParkedOrder.ParkedOrderID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pRemoveParkedOrder.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspRemoveParkedOrderAction(self, pRemoveParkedOrderAction, pRspInfo, nRequestID, bIsLast):
'''
///删除预埋撤单响应
'''
if bIsLast == True:
self.req_call['RemoveParkedOrderAction'] = 1
self.PTP_Algos.DumpRspDict("T_RemoveParkedOrderAction",pRemoveParkedOrderAction)
l_dict={}
"""CThostFtdcRemoveParkedOrderActionField
# ///经纪公司代码
l_dict["BrokerID"] = pRemoveParkedOrderAction.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pRemoveParkedOrderAction.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///预埋撤单编号
l_dict["ParkedOrderActionID"] = pRemoveParkedOrderAction.ParkedOrderActionID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pRemoveParkedOrderAction.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspExecOrderInsert(self, pInputExecOrder, pRspInfo, nRequestID, bIsLast):
'''
///执行宣告录入请求响应
'''
if bIsLast == True:
self.req_call['ExecOrderInsert'] = 1
self.PTP_Algos.DumpRspDict("T_InputExecOrder",pInputExecOrder)
l_dict={}
"""CThostFtdcInputExecOrderField
# ///经纪公司代码
l_dict["BrokerID"] = pInputExecOrder.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInputExecOrder.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pInputExecOrder.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///执行宣告引用
l_dict["ExecOrderRef"] = pInputExecOrder.ExecOrderRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pInputExecOrder.UserID.decode(encoding="gb18030", errors="ignore")
# ///数量
l_dict["Volume"] = pInputExecOrder.Volume
# ///请求编号
l_dict["RequestID"] = pInputExecOrder.RequestID
# ///业务单元
l_dict["BusinessUnit"] = pInputExecOrder.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///开平标志
l_dict["OffsetFlag"] = pInputExecOrder.OffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pInputExecOrder.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///执行类型
l_dict["ActionType"] = pInputExecOrder.ActionType.decode(encoding="gb18030", errors="ignore")
# ///保留头寸申请的持仓方向
l_dict["PosiDirection"] = pInputExecOrder.PosiDirection.decode(encoding="gb18030", errors="ignore")
# ///期权行权后是否保留期货头寸的标记,该字段已废弃
l_dict["ReservePositionFlag"] = pInputExecOrder.ReservePositionFlag.decode(encoding="gb18030", errors="ignore")
# ///期权行权后生成的头寸是否自动平仓
l_dict["CloseFlag"] = pInputExecOrder.CloseFlag.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pInputExecOrder.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInputExecOrder.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///资金账号
l_dict["AccountID"] = pInputExecOrder.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pInputExecOrder.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///交易编码
l_dict["ClientID"] = pInputExecOrder.ClientID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pInputExecOrder.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pInputExecOrder.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspExecOrderAction(self, pInputExecOrderAction, pRspInfo, nRequestID, bIsLast):
'''
///执行宣告操作请求响应
'''
if bIsLast == True:
self.req_call['ExecOrderAction'] = 1
self.PTP_Algos.DumpRspDict("T_InputExecOrderAction",pInputExecOrderAction)
l_dict={}
"""CThostFtdcInputExecOrderActionField
# ///经纪公司代码
l_dict["BrokerID"] = pInputExecOrderAction.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInputExecOrderAction.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///执行宣告操作引用
l_dict["ExecOrderActionRef"] = pInputExecOrderAction.ExecOrderActionRef
# ///执行宣告引用
l_dict["ExecOrderRef"] = pInputExecOrderAction.ExecOrderRef.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pInputExecOrderAction.RequestID
# ///前置编号
l_dict["FrontID"] = pInputExecOrderAction.FrontID
# ///会话编号
l_dict["SessionID"] = pInputExecOrderAction.SessionID
# ///交易所代码
l_dict["ExchangeID"] = pInputExecOrderAction.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///执行宣告操作编号
l_dict["ExecOrderSysID"] = pInputExecOrderAction.ExecOrderSysID.decode(encoding="gb18030", errors="ignore")
# ///操作标志
l_dict["ActionFlag"] = pInputExecOrderAction.ActionFlag.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pInputExecOrderAction.UserID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pInputExecOrderAction.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInputExecOrderAction.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pInputExecOrderAction.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pInputExecOrderAction.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspForQuoteInsert(self, pInputForQuote, pRspInfo, nRequestID, bIsLast):
'''
///询价录入请求响应
'''
if bIsLast == True:
self.req_call['ForQuoteInsert'] = 1
self.PTP_Algos.DumpRspDict("T_InputForQuote",pInputForQuote)
l_dict={}
"""CThostFtdcInputForQuoteField
# ///经纪公司代码
l_dict["BrokerID"] = pInputForQuote.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInputForQuote.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pInputForQuote.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///询价引用
l_dict["ForQuoteRef"] = pInputForQuote.ForQuoteRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pInputForQuote.UserID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pInputForQuote.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInputForQuote.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pInputForQuote.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pInputForQuote.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQuoteInsert(self, pInputQuote, pRspInfo, nRequestID, bIsLast):
'''
///报价录入请求响应
'''
if bIsLast == True:
self.req_call['QuoteInsert'] = 1
self.PTP_Algos.DumpRspDict("T_InputQuote",pInputQuote)
l_dict={}
"""CThostFtdcInputQuoteField
# ///经纪公司代码
l_dict["BrokerID"] = pInputQuote.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInputQuote.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pInputQuote.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///报价引用
l_dict["QuoteRef"] = pInputQuote.QuoteRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pInputQuote.UserID.decode(encoding="gb18030", errors="ignore")
# ///卖价格
l_dict["AskPrice"] = pInputQuote.AskPrice
# ///买价格
l_dict["BidPrice"] = pInputQuote.BidPrice
# ///卖数量
l_dict["AskVolume"] = pInputQuote.AskVolume
# ///买数量
l_dict["BidVolume"] = pInputQuote.BidVolume
# ///请求编号
l_dict["RequestID"] = pInputQuote.RequestID
# ///业务单元
l_dict["BusinessUnit"] = pInputQuote.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///卖开平标志
l_dict["AskOffsetFlag"] = pInputQuote.AskOffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///买开平标志
l_dict["BidOffsetFlag"] = pInputQuote.BidOffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///卖投机套保标志
l_dict["AskHedgeFlag"] = pInputQuote.AskHedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///买投机套保标志
l_dict["BidHedgeFlag"] = pInputQuote.BidHedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///衍生卖报单引用
l_dict["AskOrderRef"] = pInputQuote.AskOrderRef.decode(encoding="gb18030", errors="ignore")
# ///衍生买报单引用
l_dict["BidOrderRef"] = pInputQuote.BidOrderRef.decode(encoding="gb18030", errors="ignore")
# ///应价编号
l_dict["ForQuoteSysID"] = pInputQuote.ForQuoteSysID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pInputQuote.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInputQuote.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///交易编码
l_dict["ClientID"] = pInputQuote.ClientID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pInputQuote.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pInputQuote.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQuoteAction(self, pInputQuoteAction, pRspInfo, nRequestID, bIsLast):
'''
///报价操作请求响应
'''
if bIsLast == True:
self.req_call['QuoteAction'] = 1
self.PTP_Algos.DumpRspDict("T_InputQuoteAction",pInputQuoteAction)
l_dict={}
"""CThostFtdcInputQuoteActionField
# ///经纪公司代码
l_dict["BrokerID"] = pInputQuoteAction.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInputQuoteAction.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///报价操作引用
l_dict["QuoteActionRef"] = pInputQuoteAction.QuoteActionRef
# ///报价引用
l_dict["QuoteRef"] = pInputQuoteAction.QuoteRef.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pInputQuoteAction.RequestID
# ///前置编号
l_dict["FrontID"] = pInputQuoteAction.FrontID
# ///会话编号
l_dict["SessionID"] = pInputQuoteAction.SessionID
# ///交易所代码
l_dict["ExchangeID"] = pInputQuoteAction.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///报价操作编号
l_dict["QuoteSysID"] = pInputQuoteAction.QuoteSysID.decode(encoding="gb18030", errors="ignore")
# ///操作标志
l_dict["ActionFlag"] = pInputQuoteAction.ActionFlag.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pInputQuoteAction.UserID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pInputQuoteAction.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInputQuoteAction.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///交易编码
l_dict["ClientID"] = pInputQuoteAction.ClientID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pInputQuoteAction.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pInputQuoteAction.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspBatchOrderAction(self, pInputBatchOrderAction, pRspInfo, nRequestID, bIsLast):
'''
///批量报单操作请求响应
'''
if bIsLast == True:
self.req_call['BatchOrderAction'] = 1
self.PTP_Algos.DumpRspDict("T_InputBatchOrderAction",pInputBatchOrderAction)
l_dict={}
"""CThostFtdcInputBatchOrderActionField
# ///经纪公司代码
l_dict["BrokerID"] = pInputBatchOrderAction.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInputBatchOrderAction.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///报单操作引用
l_dict["OrderActionRef"] = pInputBatchOrderAction.OrderActionRef
# ///请求编号
l_dict["RequestID"] = pInputBatchOrderAction.RequestID
# ///前置编号
l_dict["FrontID"] = pInputBatchOrderAction.FrontID
# ///会话编号
l_dict["SessionID"] = pInputBatchOrderAction.SessionID
# ///交易所代码
l_dict["ExchangeID"] = pInputBatchOrderAction.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pInputBatchOrderAction.UserID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInputBatchOrderAction.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pInputBatchOrderAction.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pInputBatchOrderAction.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspOptionSelfCloseInsert(self, pInputOptionSelfClose, pRspInfo, nRequestID, bIsLast):
'''
///期权自对冲录入请求响应
'''
if bIsLast == True:
self.req_call['OptionSelfCloseInsert'] = 1
self.PTP_Algos.DumpRspDict("T_InputOptionSelfClose",pInputOptionSelfClose)
l_dict={}
"""CThostFtdcInputOptionSelfCloseField
# ///经纪公司代码
l_dict["BrokerID"] = pInputOptionSelfClose.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInputOptionSelfClose.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pInputOptionSelfClose.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///期权自对冲引用
l_dict["OptionSelfCloseRef"] = pInputOptionSelfClose.OptionSelfCloseRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pInputOptionSelfClose.UserID.decode(encoding="gb18030", errors="ignore")
# ///数量
l_dict["Volume"] = pInputOptionSelfClose.Volume
# ///请求编号
l_dict["RequestID"] = pInputOptionSelfClose.RequestID
# ///业务单元
l_dict["BusinessUnit"] = pInputOptionSelfClose.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pInputOptionSelfClose.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///期权行权的头寸是否自对冲
l_dict["OptSelfCloseFlag"] = pInputOptionSelfClose.OptSelfCloseFlag.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pInputOptionSelfClose.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInputOptionSelfClose.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///资金账号
l_dict["AccountID"] = pInputOptionSelfClose.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pInputOptionSelfClose.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///交易编码
l_dict["ClientID"] = pInputOptionSelfClose.ClientID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pInputOptionSelfClose.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pInputOptionSelfClose.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspOptionSelfCloseAction(self, pInputOptionSelfCloseAction, pRspInfo, nRequestID, bIsLast):
'''
///期权自对冲操作请求响应
'''
if bIsLast == True:
self.req_call['OptionSelfCloseAction'] = 1
self.PTP_Algos.DumpRspDict("T_InputOptionSelfCloseAction",pInputOptionSelfCloseAction)
l_dict={}
"""CThostFtdcInputOptionSelfCloseActionField
# ///经纪公司代码
l_dict["BrokerID"] = pInputOptionSelfCloseAction.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInputOptionSelfCloseAction.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///期权自对冲操作引用
l_dict["OptionSelfCloseActionRef"] = pInputOptionSelfCloseAction.OptionSelfCloseActionRef
# ///期权自对冲引用
l_dict["OptionSelfCloseRef"] = pInputOptionSelfCloseAction.OptionSelfCloseRef.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pInputOptionSelfCloseAction.RequestID
# ///前置编号
l_dict["FrontID"] = pInputOptionSelfCloseAction.FrontID
# ///会话编号
l_dict["SessionID"] = pInputOptionSelfCloseAction.SessionID
# ///交易所代码
l_dict["ExchangeID"] = pInputOptionSelfCloseAction.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///期权自对冲操作编号
l_dict["OptionSelfCloseSysID"] = pInputOptionSelfCloseAction.OptionSelfCloseSysID.decode(encoding="gb18030", errors="ignore")
# ///操作标志
l_dict["ActionFlag"] = pInputOptionSelfCloseAction.ActionFlag.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pInputOptionSelfCloseAction.UserID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pInputOptionSelfCloseAction.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInputOptionSelfCloseAction.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pInputOptionSelfCloseAction.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pInputOptionSelfCloseAction.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspCombActionInsert(self, pInputCombAction, pRspInfo, nRequestID, bIsLast):
'''
///申请组合录入请求响应
'''
if bIsLast == True:
self.req_call['CombActionInsert'] = 1
self.PTP_Algos.DumpRspDict("T_InputCombAction",pInputCombAction)
l_dict={}
"""CThostFtdcInputCombActionField
# ///经纪公司代码
l_dict["BrokerID"] = pInputCombAction.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInputCombAction.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pInputCombAction.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///组合引用
l_dict["CombActionRef"] = pInputCombAction.CombActionRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pInputCombAction.UserID.decode(encoding="gb18030", errors="ignore")
# ///买卖方向
l_dict["Direction"] = pInputCombAction.Direction.decode(encoding="gb18030", errors="ignore")
# ///数量
l_dict["Volume"] = pInputCombAction.Volume
# ///组合指令方向
l_dict["CombDirection"] = pInputCombAction.CombDirection.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pInputCombAction.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pInputCombAction.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pInputCombAction.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pInputCombAction.MacAddress.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInputCombAction.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryOrder(self, pOrder, pRspInfo, nRequestID, bIsLast):
'''
///请求查询报单响应
'''
if bIsLast == True:
self.req_call['QryOrder'] = 1
self.PTP_Algos.push_OnRspQryOrder("T_Order",pOrder)
l_dict={}
"""CThostFtdcOrderField
# ///经纪公司代码
l_dict["BrokerID"] = pOrder.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pOrder.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pOrder.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///报单引用
l_dict["OrderRef"] = pOrder.OrderRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pOrder.UserID.decode(encoding="gb18030", errors="ignore")
# ///报单价格条件
l_dict["OrderPriceType"] = pOrder.OrderPriceType.decode(encoding="gb18030", errors="ignore")
# ///买卖方向
l_dict["Direction"] = pOrder.Direction.decode(encoding="gb18030", errors="ignore")
# ///组合开平标志
l_dict["CombOffsetFlag"] = pOrder.CombOffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///组合投机套保标志
l_dict["CombHedgeFlag"] = pOrder.CombHedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///价格
l_dict["LimitPrice"] = pOrder.LimitPrice
# ///数量
l_dict["VolumeTotalOriginal"] = pOrder.VolumeTotalOriginal
# ///有效期类型
l_dict["TimeCondition"] = pOrder.TimeCondition.decode(encoding="gb18030", errors="ignore")
# ///GTD日期
l_dict["GTDDate"] = pOrder.GTDDate.decode(encoding="gb18030", errors="ignore")
# ///成交量类型
l_dict["VolumeCondition"] = pOrder.VolumeCondition.decode(encoding="gb18030", errors="ignore")
# ///最小成交量
l_dict["MinVolume"] = pOrder.MinVolume
# ///触发条件
l_dict["ContingentCondition"] = pOrder.ContingentCondition.decode(encoding="gb18030", errors="ignore")
# ///止损价
l_dict["StopPrice"] = pOrder.StopPrice
# ///强平原因
l_dict["ForceCloseReason"] = pOrder.ForceCloseReason.decode(encoding="gb18030", errors="ignore")
# ///自动挂起标志
l_dict["IsAutoSuspend"] = pOrder.IsAutoSuspend
# ///业务单元
l_dict["BusinessUnit"] = pOrder.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pOrder.RequestID
# ///本地报单编号
l_dict["OrderLocalID"] = pOrder.OrderLocalID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pOrder.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pOrder.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pOrder.ClientID.decode(encoding="gb18030", errors="ignore")
# ///合约在交易所的代码
l_dict["ExchangeInstID"] = pOrder.ExchangeInstID.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pOrder.TraderID.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pOrder.InstallID
# ///报单提交状态
l_dict["OrderSubmitStatus"] = pOrder.OrderSubmitStatus.decode(encoding="gb18030", errors="ignore")
# ///报单提示序号
l_dict["NotifySequence"] = pOrder.NotifySequence
# ///交易日
l_dict["TradingDay"] = pOrder.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pOrder.SettlementID
# ///报单编号
l_dict["OrderSysID"] = pOrder.OrderSysID.decode(encoding="gb18030", errors="ignore")
# ///报单来源
l_dict["OrderSource"] = pOrder.OrderSource.decode(encoding="gb18030", errors="ignore")
# ///报单状态
l_dict["OrderStatus"] = pOrder.OrderStatus.decode(encoding="gb18030", errors="ignore")
# ///报单类型
l_dict["OrderType"] = pOrder.OrderType.decode(encoding="gb18030", errors="ignore")
# ///今成交数量
l_dict["VolumeTraded"] = pOrder.VolumeTraded
# ///剩余数量
l_dict["VolumeTotal"] = pOrder.VolumeTotal
# ///报单日期
l_dict["InsertDate"] = pOrder.InsertDate.decode(encoding="gb18030", errors="ignore")
# ///委托时间
l_dict["InsertTime"] = pOrder.InsertTime.decode(encoding="gb18030", errors="ignore")
# ///激活时间
l_dict["ActiveTime"] = pOrder.ActiveTime.decode(encoding="gb18030", errors="ignore")
# ///挂起时间
l_dict["SuspendTime"] = pOrder.SuspendTime.decode(encoding="gb18030", errors="ignore")
# ///最后修改时间
l_dict["UpdateTime"] = pOrder.UpdateTime.decode(encoding="gb18030", errors="ignore")
# ///撤销时间
l_dict["CancelTime"] = pOrder.CancelTime.decode(encoding="gb18030", errors="ignore")
# ///最后修改交易所交易员代码
l_dict["ActiveTraderID"] = pOrder.ActiveTraderID.decode(encoding="gb18030", errors="ignore")
# ///结算会员编号
l_dict["ClearingPartID"] = pOrder.ClearingPartID.decode(encoding="gb18030", errors="ignore")
# ///序号
l_dict["SequenceNo"] = pOrder.SequenceNo
# ///前置编号
l_dict["FrontID"] = pOrder.FrontID
# ///会话编号
l_dict["SessionID"] = pOrder.SessionID
# ///用户端产品信息
l_dict["UserProductInfo"] = pOrder.UserProductInfo.decode(encoding="gb18030", errors="ignore")
# ///状态信息
l_dict["StatusMsg"] = pOrder.StatusMsg.decode(encoding="gb18030", errors="ignore")
# ///用户强评标志
l_dict["UserForceClose"] = pOrder.UserForceClose
# ///操作用户代码
l_dict["ActiveUserID"] = pOrder.ActiveUserID.decode(encoding="gb18030", errors="ignore")
# ///经纪公司报单编号
l_dict["BrokerOrderSeq"] = pOrder.BrokerOrderSeq
# ///相关报单
l_dict["RelativeOrderSysID"] = pOrder.RelativeOrderSysID.decode(encoding="gb18030", errors="ignore")
# ///郑商所成交数量
l_dict["ZCETotalTradedVolume"] = pOrder.ZCETotalTradedVolume
# ///互换单标志
l_dict["IsSwapOrder"] = pOrder.IsSwapOrder
# ///营业部编号
l_dict["BranchID"] = pOrder.BranchID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pOrder.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///资金账号
l_dict["AccountID"] = pOrder.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pOrder.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pOrder.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pOrder.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryTrade(self, pTrade, pRspInfo, nRequestID, bIsLast):
'''
///请求查询成交响应
'''
if bIsLast == True:
self.req_call['QryTrade'] = 1
self.PTP_Algos.DumpRspDict("T_Trade",pTrade)
l_dict={}
"""CThostFtdcTradeField
# ///经纪公司代码
l_dict["BrokerID"] = pTrade.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pTrade.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pTrade.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///报单引用
l_dict["OrderRef"] = pTrade.OrderRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pTrade.UserID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pTrade.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///成交编号
l_dict["TradeID"] = pTrade.TradeID.decode(encoding="gb18030", errors="ignore")
# ///买卖方向
l_dict["Direction"] = pTrade.Direction.decode(encoding="gb18030", errors="ignore")
# ///报单编号
l_dict["OrderSysID"] = pTrade.OrderSysID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pTrade.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pTrade.ClientID.decode(encoding="gb18030", errors="ignore")
# ///交易角色
l_dict["TradingRole"] = pTrade.TradingRole.decode(encoding="gb18030", errors="ignore")
# ///合约在交易所的代码
l_dict["ExchangeInstID"] = pTrade.ExchangeInstID.decode(encoding="gb18030", errors="ignore")
# ///开平标志
l_dict["OffsetFlag"] = pTrade.OffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pTrade.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///价格
l_dict["Price"] = pTrade.Price
# ///数量
l_dict["Volume"] = pTrade.Volume
# ///成交时期
l_dict["TradeDate"] = pTrade.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///成交时间
l_dict["TradeTime"] = pTrade.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///成交类型
l_dict["TradeType"] = pTrade.TradeType.decode(encoding="gb18030", errors="ignore")
# ///成交价来源
l_dict["PriceSource"] = pTrade.PriceSource.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pTrade.TraderID.decode(encoding="gb18030", errors="ignore")
# ///本地报单编号
l_dict["OrderLocalID"] = pTrade.OrderLocalID.decode(encoding="gb18030", errors="ignore")
# ///结算会员编号
l_dict["ClearingPartID"] = pTrade.ClearingPartID.decode(encoding="gb18030", errors="ignore")
# ///业务单元
l_dict["BusinessUnit"] = pTrade.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///序号
l_dict["SequenceNo"] = pTrade.SequenceNo
# ///交易日
l_dict["TradingDay"] = pTrade.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pTrade.SettlementID
# ///经纪公司报单编号
l_dict["BrokerOrderSeq"] = pTrade.BrokerOrderSeq
# ///成交来源
l_dict["TradeSource"] = pTrade.TradeSource.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pTrade.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryInvestorPosition(self, pInvestorPosition, pRspInfo, nRequestID, bIsLast):
'''
///请求查询投资者持仓响应
'''
if bIsLast == True:
self.req_call['QryInvestorPosition'] = 1
self.PTP_Algos.push_OnRspQryInvestorPosition("T_InvestorPosition",pInvestorPosition)
l_dict={}
"""CThostFtdcInvestorPositionField
# ///合约代码
l_dict["InstrumentID"] = pInvestorPosition.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///经纪公司代码
l_dict["BrokerID"] = pInvestorPosition.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInvestorPosition.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///持仓多空方向
l_dict["PosiDirection"] = pInvestorPosition.PosiDirection.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pInvestorPosition.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///持仓日期
l_dict["PositionDate"] = pInvestorPosition.PositionDate.decode(encoding="gb18030", errors="ignore")
# ///上日持仓
l_dict["YdPosition"] = pInvestorPosition.YdPosition
# ///今日持仓
l_dict["Position"] = pInvestorPosition.Position
# ///多头冻结
l_dict["LongFrozen"] = pInvestorPosition.LongFrozen
# ///空头冻结
l_dict["ShortFrozen"] = pInvestorPosition.ShortFrozen
# ///开仓冻结金额
l_dict["LongFrozenAmount"] = pInvestorPosition.LongFrozenAmount
# ///开仓冻结金额
l_dict["ShortFrozenAmount"] = pInvestorPosition.ShortFrozenAmount
# ///开仓量
l_dict["OpenVolume"] = pInvestorPosition.OpenVolume
# ///平仓量
l_dict["CloseVolume"] = pInvestorPosition.CloseVolume
# ///开仓金额
l_dict["OpenAmount"] = pInvestorPosition.OpenAmount
# ///平仓金额
l_dict["CloseAmount"] = pInvestorPosition.CloseAmount
# ///持仓成本
l_dict["PositionCost"] = pInvestorPosition.PositionCost
# ///上次占用的保证金
l_dict["PreMargin"] = pInvestorPosition.PreMargin
# ///占用的保证金
l_dict["UseMargin"] = pInvestorPosition.UseMargin
# ///冻结的保证金
l_dict["FrozenMargin"] = pInvestorPosition.FrozenMargin
# ///冻结的资金
l_dict["FrozenCash"] = pInvestorPosition.FrozenCash
# ///冻结的手续费
l_dict["FrozenCommission"] = pInvestorPosition.FrozenCommission
# ///资金差额
l_dict["CashIn"] = pInvestorPosition.CashIn
# ///手续费
l_dict["Commission"] = pInvestorPosition.Commission
# ///平仓盈亏
l_dict["CloseProfit"] = pInvestorPosition.CloseProfit
# ///持仓盈亏
l_dict["PositionProfit"] = pInvestorPosition.PositionProfit
# ///上次结算价
l_dict["PreSettlementPrice"] = pInvestorPosition.PreSettlementPrice
# ///本次结算价
l_dict["SettlementPrice"] = pInvestorPosition.SettlementPrice
# ///交易日
l_dict["TradingDay"] = pInvestorPosition.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pInvestorPosition.SettlementID
# ///开仓成本
l_dict["OpenCost"] = pInvestorPosition.OpenCost
# ///交易所保证金
l_dict["ExchangeMargin"] = pInvestorPosition.ExchangeMargin
# ///组合成交形成的持仓
l_dict["CombPosition"] = pInvestorPosition.CombPosition
# ///组合多头冻结
l_dict["CombLongFrozen"] = pInvestorPosition.CombLongFrozen
# ///组合空头冻结
l_dict["CombShortFrozen"] = pInvestorPosition.CombShortFrozen
# ///逐日盯市平仓盈亏
l_dict["CloseProfitByDate"] = pInvestorPosition.CloseProfitByDate
# ///逐笔对冲平仓盈亏
l_dict["CloseProfitByTrade"] = pInvestorPosition.CloseProfitByTrade
# ///今日持仓
l_dict["TodayPosition"] = pInvestorPosition.TodayPosition
# ///保证金率
l_dict["MarginRateByMoney"] = pInvestorPosition.MarginRateByMoney
# ///保证金率(按手数)
l_dict["MarginRateByVolume"] = pInvestorPosition.MarginRateByVolume
# ///执行冻结
l_dict["StrikeFrozen"] = pInvestorPosition.StrikeFrozen
# ///执行冻结金额
l_dict["StrikeFrozenAmount"] = pInvestorPosition.StrikeFrozenAmount
# ///放弃执行冻结
l_dict["AbandonFrozen"] = pInvestorPosition.AbandonFrozen
# ///交易所代码
l_dict["ExchangeID"] = pInvestorPosition.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///执行冻结的昨仓
l_dict["YdStrikeFrozen"] = pInvestorPosition.YdStrikeFrozen
# ///投资单元代码
l_dict["InvestUnitID"] = pInvestorPosition.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryTradingAccount(self, pTradingAccount, pRspInfo, nRequestID, bIsLast):
'''
///请求查询资金账户响应
'''
if bIsLast == True:
self.req_call['QryTradingAccount'] = 1
self.PTP_Algos.push_OnRspQryTradingAccount("T_TradingAccount",pTradingAccount)
l_dict={}
"""CThostFtdcTradingAccountField
# ///经纪公司代码
l_dict["BrokerID"] = pTradingAccount.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pTradingAccount.AccountID.decode(encoding="gb18030", errors="ignore")
# ///上次质押金额
l_dict["PreMortgage"] = pTradingAccount.PreMortgage
# ///上次信用额度
l_dict["PreCredit"] = pTradingAccount.PreCredit
# ///上次存款额
l_dict["PreDeposit"] = pTradingAccount.PreDeposit
# ///上次结算准备金
l_dict["PreBalance"] = pTradingAccount.PreBalance
# ///上次占用的保证金
l_dict["PreMargin"] = pTradingAccount.PreMargin
# ///利息基数
l_dict["InterestBase"] = pTradingAccount.InterestBase
# ///利息收入
l_dict["Interest"] = pTradingAccount.Interest
# ///入金金额
l_dict["Deposit"] = pTradingAccount.Deposit
# ///出金金额
l_dict["Withdraw"] = pTradingAccount.Withdraw
# ///冻结的保证金
l_dict["FrozenMargin"] = pTradingAccount.FrozenMargin
# ///冻结的资金
l_dict["FrozenCash"] = pTradingAccount.FrozenCash
# ///冻结的手续费
l_dict["FrozenCommission"] = pTradingAccount.FrozenCommission
# ///当前保证金总额
l_dict["CurrMargin"] = pTradingAccount.CurrMargin
# ///资金差额
l_dict["CashIn"] = pTradingAccount.CashIn
# ///手续费
l_dict["Commission"] = pTradingAccount.Commission
# ///平仓盈亏
l_dict["CloseProfit"] = pTradingAccount.CloseProfit
# ///持仓盈亏
l_dict["PositionProfit"] = pTradingAccount.PositionProfit
# ///期货结算准备金
l_dict["Balance"] = pTradingAccount.Balance
# ///可用资金
l_dict["Available"] = pTradingAccount.Available
# ///可取资金
l_dict["WithdrawQuota"] = pTradingAccount.WithdrawQuota
# ///基本准备金
l_dict["Reserve"] = pTradingAccount.Reserve
# ///交易日
l_dict["TradingDay"] = pTradingAccount.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pTradingAccount.SettlementID
# ///信用额度
l_dict["Credit"] = pTradingAccount.Credit
# ///质押金额
l_dict["Mortgage"] = pTradingAccount.Mortgage
# ///交易所保证金
l_dict["ExchangeMargin"] = pTradingAccount.ExchangeMargin
# ///投资者交割保证金
l_dict["DeliveryMargin"] = pTradingAccount.DeliveryMargin
# ///交易所交割保证金
l_dict["ExchangeDeliveryMargin"] = pTradingAccount.ExchangeDeliveryMargin
# ///保底期货结算准备金
l_dict["ReserveBalance"] = pTradingAccount.ReserveBalance
# ///币种代码
l_dict["CurrencyID"] = pTradingAccount.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///上次货币质入金额
l_dict["PreFundMortgageIn"] = pTradingAccount.PreFundMortgageIn
# ///上次货币质出金额
l_dict["PreFundMortgageOut"] = pTradingAccount.PreFundMortgageOut
# ///货币质入金额
l_dict["FundMortgageIn"] = pTradingAccount.FundMortgageIn
# ///货币质出金额
l_dict["FundMortgageOut"] = pTradingAccount.FundMortgageOut
# ///货币质押余额
l_dict["FundMortgageAvailable"] = pTradingAccount.FundMortgageAvailable
# ///可质押货币金额
l_dict["MortgageableFund"] = pTradingAccount.MortgageableFund
# ///特殊产品占用保证金
l_dict["SpecProductMargin"] = pTradingAccount.SpecProductMargin
# ///特殊产品冻结保证金
l_dict["SpecProductFrozenMargin"] = pTradingAccount.SpecProductFrozenMargin
# ///特殊产品手续费
l_dict["SpecProductCommission"] = pTradingAccount.SpecProductCommission
# ///特殊产品冻结手续费
l_dict["SpecProductFrozenCommission = pTradingAccount.SpecProductFrozenCommission
# ///特殊产品持仓盈亏
l_dict["SpecProductPositionProfit"] = pTradingAccount.SpecProductPositionProfit
# ///特殊产品平仓盈亏
l_dict["SpecProductCloseProfit"] = pTradingAccount.SpecProductCloseProfit
# ///根据持仓盈亏算法计算的特殊产品持仓盈亏
l_dict["SpecProductPositionProfitBy = pTradingAccount.SpecProductPositionProfitByAlg
# ///特殊产品交易所保证金
l_dict["SpecProductExchangeMargin"] = pTradingAccount.SpecProductExchangeMargin
# ///业务类型
l_dict["BizType"] = pTradingAccount.BizType.decode(encoding="gb18030", errors="ignore")
# ///延时换汇冻结金额
l_dict["FrozenSwap"] = pTradingAccount.FrozenSwap
# ///剩余换汇额度
l_dict["RemainSwap"] = pTradingAccount.RemainSwap
#"""
def OnRspQryInvestor(self, pInvestor, pRspInfo, nRequestID, bIsLast):
'''
///请求查询投资者响应
'''
if bIsLast == True:
self.req_call['QryInvestor'] = 1
self.PTP_Algos.DumpRspDict("T_Investor",pInvestor)
l_dict={}
"""CThostFtdcInvestorField
# ///投资者代码
l_dict["InvestorID"] = pInvestor.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///经纪公司代码
l_dict["BrokerID"] = pInvestor.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者分组代码
l_dict["InvestorGroupID"] = pInvestor.InvestorGroupID.decode(encoding="gb18030", errors="ignore")
# ///投资者名称
l_dict["InvestorName"] = pInvestor.InvestorName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdentifiedCardType"] = pInvestor.IdentifiedCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pInvestor.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///是否活跃
l_dict["IsActive"] = pInvestor.IsActive
# ///联系电话
l_dict["Telephone"] = pInvestor.Telephone.decode(encoding="gb18030", errors="ignore")
# ///通讯地址
l_dict["Address"] = pInvestor.Address.decode(encoding="gb18030", errors="ignore")
# ///开户日期
l_dict["OpenDate"] = pInvestor.OpenDate.decode(encoding="gb18030", errors="ignore")
# ///手机
l_dict["Mobile"] = pInvestor.Mobile.decode(encoding="gb18030", errors="ignore")
# ///手续费率模板代码
l_dict["CommModelID"] = pInvestor.CommModelID.decode(encoding="gb18030", errors="ignore")
# ///保证金率模板代码
l_dict["MarginModelID"] = pInvestor.MarginModelID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryTradingCode(self, pTradingCode, pRspInfo, nRequestID, bIsLast):
'''
///请求查询交易编码响应
'''
if bIsLast == True:
self.req_call['QryTradingCode'] = 1
self.PTP_Algos.DumpRspDict("T_TradingCode",pTradingCode)
l_dict={}
"""CThostFtdcTradingCodeField
# ///投资者代码
l_dict["InvestorID"] = pTradingCode.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///经纪公司代码
l_dict["BrokerID"] = pTradingCode.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pTradingCode.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pTradingCode.ClientID.decode(encoding="gb18030", errors="ignore")
# ///是否活跃
l_dict["IsActive"] = pTradingCode.IsActive
# ///交易编码类型
l_dict["ClientIDType"] = pTradingCode.ClientIDType.decode(encoding="gb18030", errors="ignore")
# ///营业部编号
l_dict["BranchID"] = pTradingCode.BranchID.decode(encoding="gb18030", errors="ignore")
# ///业务类型
l_dict["BizType"] = pTradingCode.BizType.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pTradingCode.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryInstrumentMarginRate(self, pInstrumentMarginRate, pRspInfo, nRequestID, bIsLast):
'''
///请求查询合约保证金率响应
'''
if bIsLast == True:
self.req_call['QryInstrumentMarginRate'] = 1
self.PTP_Algos.DumpRspDict("T_InstrumentMarginRate",pInstrumentMarginRate)
l_dict={}
"""CThostFtdcInstrumentMarginRateField
# ///合约代码
l_dict["InstrumentID"] = pInstrumentMarginRate.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///投资者范围
l_dict["InvestorRange"] = pInstrumentMarginRate.InvestorRange.decode(encoding="gb18030", errors="ignore")
# ///经纪公司代码
l_dict["BrokerID"] = pInstrumentMarginRate.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInstrumentMarginRate.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pInstrumentMarginRate.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///多头保证金率
l_dict["LongMarginRatioByMoney"] = pInstrumentMarginRate.LongMarginRatioByMoney
# ///多头保证金费
l_dict["LongMarginRatioByVolume"] = pInstrumentMarginRate.LongMarginRatioByVolume
# ///空头保证金率
l_dict["ShortMarginRatioByMoney"] = pInstrumentMarginRate.ShortMarginRatioByMoney
# ///空头保证金费
l_dict["ShortMarginRatioByVolume"] = pInstrumentMarginRate.ShortMarginRatioByVolume
# ///是否相对交易所收取
l_dict["IsRelative"] = pInstrumentMarginRate.IsRelative
# ///交易所代码
l_dict["ExchangeID"] = pInstrumentMarginRate.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInstrumentMarginRate.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryInstrumentCommissionRate(self, pInstrumentCommissionRate, pRspInfo, nRequestID, bIsLast):
'''
///请求查询合约手续费率响应
'''
if bIsLast == True:
self.req_call['QryInstrumentCommissionRate'] = 1
self.PTP_Algos.DumpRspDict("T_InstrumentCommissionRate",pInstrumentCommissionRate)
l_dict={}
"""CThostFtdcInstrumentCommissionRateField
# ///合约代码
l_dict["InstrumentID"] = pInstrumentCommissionRate.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///投资者范围
l_dict["InvestorRange"] = pInstrumentCommissionRate.InvestorRange.decode(encoding="gb18030", errors="ignore")
# ///经纪公司代码
l_dict["BrokerID"] = pInstrumentCommissionRate.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInstrumentCommissionRate.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///开仓手续费率
l_dict["OpenRatioByMoney"] = pInstrumentCommissionRate.OpenRatioByMoney
# ///开仓手续费
l_dict["OpenRatioByVolume"] = pInstrumentCommissionRate.OpenRatioByVolume
# ///平仓手续费率
l_dict["CloseRatioByMoney"] = pInstrumentCommissionRate.CloseRatioByMoney
# ///平仓手续费
l_dict["CloseRatioByVolume"] = pInstrumentCommissionRate.CloseRatioByVolume
# ///平今手续费率
l_dict["CloseTodayRatioByMoney"] = pInstrumentCommissionRate.CloseTodayRatioByMoney
# ///平今手续费
l_dict["CloseTodayRatioByVolume"] = pInstrumentCommissionRate.CloseTodayRatioByVolume
# ///交易所代码
l_dict["ExchangeID"] = pInstrumentCommissionRate.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///业务类型
l_dict["BizType"] = pInstrumentCommissionRate.BizType.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInstrumentCommissionRate.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryExchange(self, pExchange, pRspInfo, nRequestID, bIsLast):
'''
///请求查询交易所响应
'''
if bIsLast == True:
self.req_call['QryExchange'] = 1
self.PTP_Algos.DumpRspDict("T_Exchange",pExchange)
l_dict={}
"""CThostFtdcExchangeField
# ///交易所代码
l_dict["ExchangeID"] = pExchange.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///交易所名称
l_dict["ExchangeName"] = pExchange.ExchangeName.decode(encoding="gb18030", errors="ignore")
# ///交易所属性
l_dict["ExchangeProperty"] = pExchange.ExchangeProperty.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryProduct(self, pProduct, pRspInfo, nRequestID, bIsLast):
'''
///请求查询产品响应
'''
if bIsLast == True:
self.req_call['QryProduct'] = 1
self.PTP_Algos.DumpRspDict("T_Product",pProduct)
l_dict={}
"""CThostFtdcProductField
# ///产品代码
l_dict["ProductID"] = pProduct.ProductID.decode(encoding="gb18030", errors="ignore")
# ///产品名称
l_dict["ProductName"] = pProduct.ProductName.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pProduct.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///产品类型
l_dict["ProductClass"] = pProduct.ProductClass.decode(encoding="gb18030", errors="ignore")
# ///合约数量乘数
l_dict["VolumeMultiple"] = pProduct.VolumeMultiple
# ///最小变动价位
l_dict["PriceTick"] = pProduct.PriceTick
# ///市价单最大下单量
l_dict["MaxMarketOrderVolume"] = pProduct.MaxMarketOrderVolume
# ///市价单最小下单量
l_dict["MinMarketOrderVolume"] = pProduct.MinMarketOrderVolume
# ///限价单最大下单量
l_dict["MaxLimitOrderVolume"] = pProduct.MaxLimitOrderVolume
# ///限价单最小下单量
l_dict["MinLimitOrderVolume"] = pProduct.MinLimitOrderVolume
# ///持仓类型
l_dict["PositionType"] = pProduct.PositionType.decode(encoding="gb18030", errors="ignore")
# ///持仓日期类型
l_dict["PositionDateType"] = pProduct.PositionDateType.decode(encoding="gb18030", errors="ignore")
# ///平仓处理类型
l_dict["CloseDealType"] = pProduct.CloseDealType.decode(encoding="gb18030", errors="ignore")
# ///交易币种类型
l_dict["TradeCurrencyID"] = pProduct.TradeCurrencyID.decode(encoding="gb18030", errors="ignore")
# ///质押资金可用范围
l_dict["MortgageFundUseRange"] = pProduct.MortgageFundUseRange.decode(encoding="gb18030", errors="ignore")
# ///交易所产品代码
l_dict["ExchangeProductID"] = pProduct.ExchangeProductID.decode(encoding="gb18030", errors="ignore")
# ///合约基础商品乘数
l_dict["UnderlyingMultiple"] = pProduct.UnderlyingMultiple
#"""
def OnRspQryInstrument(self, pInstrument, pRspInfo, nRequestID, bIsLast):
'''
///请求查询合约响应
'''
if bIsLast == True:
self.req_call['QryInstrument'] = 1
self.PTP_Algos.push_OnRspQryInstrument("T_Instrument",pInstrument)
l_dict={}
"""CThostFtdcInstrumentField
# ///合约代码
l_dict["InstrumentID"] = pInstrument.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pInstrument.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///合约名称
l_dict["InstrumentName"] = pInstrument.InstrumentName.decode(encoding="gb18030", errors="ignore")
# ///合约在交易所的代码
l_dict["ExchangeInstID"] = pInstrument.ExchangeInstID.decode(encoding="gb18030", errors="ignore")
# ///产品代码
l_dict["ProductID"] = pInstrument.ProductID.decode(encoding="gb18030", errors="ignore")
# ///产品类型
l_dict["ProductClass"] = pInstrument.ProductClass.decode(encoding="gb18030", errors="ignore")
# ///交割年份
l_dict["DeliveryYear"] = pInstrument.DeliveryYear
# ///交割月
l_dict["DeliveryMonth"] = pInstrument.DeliveryMonth
# ///市价单最大下单量
l_dict["MaxMarketOrderVolume"] = pInstrument.MaxMarketOrderVolume
# ///市价单最小下单量
l_dict["MinMarketOrderVolume"] = pInstrument.MinMarketOrderVolume
# ///限价单最大下单量
l_dict["MaxLimitOrderVolume"] = pInstrument.MaxLimitOrderVolume
# ///限价单最小下单量
l_dict["MinLimitOrderVolume"] = pInstrument.MinLimitOrderVolume
# ///合约数量乘数
l_dict["VolumeMultiple"] = pInstrument.VolumeMultiple
# ///最小变动价位
l_dict["PriceTick"] = pInstrument.PriceTick
# ///创建日
l_dict["CreateDate"] = pInstrument.CreateDate.decode(encoding="gb18030", errors="ignore")
# ///上市日
l_dict["OpenDate"] = pInstrument.OpenDate.decode(encoding="gb18030", errors="ignore")
# ///到期日
l_dict["ExpireDate"] = pInstrument.ExpireDate.decode(encoding="gb18030", errors="ignore")
# ///开始交割日
l_dict["StartDelivDate"] = pInstrument.StartDelivDate.decode(encoding="gb18030", errors="ignore")
# ///结束交割日
l_dict["EndDelivDate"] = pInstrument.EndDelivDate.decode(encoding="gb18030", errors="ignore")
# ///合约生命周期状态
l_dict["InstLifePhase"] = pInstrument.InstLifePhase.decode(encoding="gb18030", errors="ignore")
# ///当前是否交易
l_dict["IsTrading"] = pInstrument.IsTrading
# ///持仓类型
l_dict["PositionType"] = pInstrument.PositionType.decode(encoding="gb18030", errors="ignore")
# ///持仓日期类型
l_dict["PositionDateType"] = pInstrument.PositionDateType.decode(encoding="gb18030", errors="ignore")
# ///多头保证金率
l_dict["LongMarginRatio"] = pInstrument.LongMarginRatio
# ///空头保证金率
l_dict["ShortMarginRatio"] = pInstrument.ShortMarginRatio
# ///是否使用大额单边保证金算法
l_dict["MaxMarginSideAlgorithm"] = pInstrument.MaxMarginSideAlgorithm.decode(encoding="gb18030", errors="ignore")
# ///基础商品代码
l_dict["UnderlyingInstrID"] = pInstrument.UnderlyingInstrID.decode(encoding="gb18030", errors="ignore")
# ///执行价
l_dict["StrikePrice"] = pInstrument.StrikePrice
# ///期权类型
l_dict["OptionsType"] = pInstrument.OptionsType.decode(encoding="gb18030", errors="ignore")
# ///合约基础商品乘数
l_dict["UnderlyingMultiple"] = pInstrument.UnderlyingMultiple
# ///组合类型
l_dict["CombinationType"] = pInstrument.CombinationType.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryDepthMarketData(self, pDepthMarketData, pRspInfo, nRequestID, bIsLast):
'''
///请求查询行情响应
'''
if bIsLast == True:
self.req_call['QryDepthMarketData'] = 1
self.PTP_Algos.DumpRspDict("T_DepthMarketData",pDepthMarketData)
l_dict={}
"""CThostFtdcDepthMarketDataField
# ///交易日
l_dict["TradingDay"] = pDepthMarketData.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pDepthMarketData.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pDepthMarketData.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///合约在交易所的代码
l_dict["ExchangeInstID"] = pDepthMarketData.ExchangeInstID.decode(encoding="gb18030", errors="ignore")
# ///最新价
l_dict["LastPrice"] = pDepthMarketData.LastPrice
# ///上次结算价
l_dict["PreSettlementPrice"] = pDepthMarketData.PreSettlementPrice
# ///昨收盘
l_dict["PreClosePrice"] = pDepthMarketData.PreClosePrice
# ///昨持仓量
l_dict["PreOpenInterest"] = pDepthMarketData.PreOpenInterest
# ///今开盘
l_dict["OpenPrice"] = pDepthMarketData.OpenPrice
# ///最高价
l_dict["HighestPrice"] = pDepthMarketData.HighestPrice
# ///最低价
l_dict["LowestPrice"] = pDepthMarketData.LowestPrice
# ///数量
l_dict["Volume"] = pDepthMarketData.Volume
# ///成交金额
l_dict["Turnover"] = pDepthMarketData.Turnover
# ///持仓量
l_dict["OpenInterest"] = pDepthMarketData.OpenInterest
# ///今收盘
l_dict["ClosePrice"] = pDepthMarketData.ClosePrice
# ///本次结算价
l_dict["SettlementPrice"] = pDepthMarketData.SettlementPrice
# ///涨停板价
l_dict["UpperLimitPrice"] = pDepthMarketData.UpperLimitPrice
# ///跌停板价
l_dict["LowerLimitPrice"] = pDepthMarketData.LowerLimitPrice
# ///昨虚实度
l_dict["PreDelta"] = pDepthMarketData.PreDelta
# ///今虚实度
l_dict["CurrDelta"] = pDepthMarketData.CurrDelta
# ///最后修改时间
l_dict["UpdateTime"] = pDepthMarketData.UpdateTime.decode(encoding="gb18030", errors="ignore")
# ///最后修改毫秒
l_dict["UpdateMillisec"] = pDepthMarketData.UpdateMillisec
# ///申买价一
l_dict["BidPrice1"] = pDepthMarketData.BidPrice1
# ///申买量一
l_dict["BidVolume1"] = pDepthMarketData.BidVolume1
# ///申卖价一
l_dict["AskPrice1"] = pDepthMarketData.AskPrice1
# ///申卖量一
l_dict["AskVolume1"] = pDepthMarketData.AskVolume1
# ///申买价二
l_dict["BidPrice2"] = pDepthMarketData.BidPrice2
# ///申买量二
l_dict["BidVolume2"] = pDepthMarketData.BidVolume2
# ///申卖价二
l_dict["AskPrice2"] = pDepthMarketData.AskPrice2
# ///申卖量二
l_dict["AskVolume2"] = pDepthMarketData.AskVolume2
# ///申买价三
l_dict["BidPrice3"] = pDepthMarketData.BidPrice3
# ///申买量三
l_dict["BidVolume3"] = pDepthMarketData.BidVolume3
# ///申卖价三
l_dict["AskPrice3"] = pDepthMarketData.AskPrice3
# ///申卖量三
l_dict["AskVolume3"] = pDepthMarketData.AskVolume3
# ///申买价四
l_dict["BidPrice4"] = pDepthMarketData.BidPrice4
# ///申买量四
l_dict["BidVolume4"] = pDepthMarketData.BidVolume4
# ///申卖价四
l_dict["AskPrice4"] = pDepthMarketData.AskPrice4
# ///申卖量四
l_dict["AskVolume4"] = pDepthMarketData.AskVolume4
# ///申买价五
l_dict["BidPrice5"] = pDepthMarketData.BidPrice5
# ///申买量五
l_dict["BidVolume5"] = pDepthMarketData.BidVolume5
# ///申卖价五
l_dict["AskPrice5"] = pDepthMarketData.AskPrice5
# ///申卖量五
l_dict["AskVolume5"] = pDepthMarketData.AskVolume5
# ///当日均价
l_dict["AveragePrice"] = pDepthMarketData.AveragePrice
# ///业务日期
l_dict["ActionDay"] = pDepthMarketData.ActionDay.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQrySettlementInfo(self, pSettlementInfo, pRspInfo, nRequestID, bIsLast):
'''
///请求查询投资者结算结果响应
'''
if bIsLast == True:
self.req_call['QrySettlementInfo'] = 1
self.PTP_Algos.push_OnRspQrySettlementInfo("T_SettlementInfo",pSettlementInfo)
l_dict={}
"""CThostFtdcSettlementInfoField
# ///交易日
l_dict["TradingDay"] = pSettlementInfo.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pSettlementInfo.SettlementID
# ///经纪公司代码
l_dict["BrokerID"] = pSettlementInfo.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pSettlementInfo.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///序号
l_dict["SequenceNo"] = pSettlementInfo.SequenceNo
# ///消息正文
l_dict["Content"] = pSettlementInfo.Content.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pSettlementInfo.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pSettlementInfo.CurrencyID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryTransferBank(self, pTransferBank, pRspInfo, nRequestID, bIsLast):
'''
///请求查询转帐银行响应
'''
if bIsLast == True:
self.req_call['QryTransferBank'] = 1
self.PTP_Algos.DumpRspDict("T_TransferBank",pTransferBank)
l_dict={}
"""CThostFtdcTransferBankField
# ///银行代码
l_dict["BankID"] = pTransferBank.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分中心代码
l_dict["BankBrchID"] = pTransferBank.BankBrchID.decode(encoding="gb18030", errors="ignore")
# ///银行名称
l_dict["BankName"] = pTransferBank.BankName.decode(encoding="gb18030", errors="ignore")
# ///是否活跃
l_dict["IsActive"] = pTransferBank.IsActive
#"""
def OnRspQryInvestorPositionDetail(self, pInvestorPositionDetail, pRspInfo, nRequestID, bIsLast):
'''
///请求查询投资者持仓明细响应
'''
if bIsLast == True:
self.req_call['QryInvestorPositionDetail'] = 1
self.PTP_Algos.DumpRspDict("T_InvestorPositionDetail",pInvestorPositionDetail)
l_dict={}
"""CThostFtdcInvestorPositionDetailField
# ///合约代码
l_dict["InstrumentID"] = pInvestorPositionDetail.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///经纪公司代码
l_dict["BrokerID"] = pInvestorPositionDetail.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInvestorPositionDetail.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pInvestorPositionDetail.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///买卖
l_dict["Direction"] = pInvestorPositionDetail.Direction.decode(encoding="gb18030", errors="ignore")
# ///开仓日期
l_dict["OpenDate"] = pInvestorPositionDetail.OpenDate.decode(encoding="gb18030", errors="ignore")
# ///成交编号
l_dict["TradeID"] = pInvestorPositionDetail.TradeID.decode(encoding="gb18030", errors="ignore")
# ///数量
l_dict["Volume"] = pInvestorPositionDetail.Volume
# ///开仓价
l_dict["OpenPrice"] = pInvestorPositionDetail.OpenPrice
# ///交易日
l_dict["TradingDay"] = pInvestorPositionDetail.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pInvestorPositionDetail.SettlementID
# ///成交类型
l_dict["TradeType"] = pInvestorPositionDetail.TradeType.decode(encoding="gb18030", errors="ignore")
# ///组合合约代码
l_dict["CombInstrumentID"] = pInvestorPositionDetail.CombInstrumentID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pInvestorPositionDetail.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///逐日盯市平仓盈亏
l_dict["CloseProfitByDate"] = pInvestorPositionDetail.CloseProfitByDate
# ///逐笔对冲平仓盈亏
l_dict["CloseProfitByTrade"] = pInvestorPositionDetail.CloseProfitByTrade
# ///逐日盯市持仓盈亏
l_dict["PositionProfitByDate"] = pInvestorPositionDetail.PositionProfitByDate
# ///逐笔对冲持仓盈亏
l_dict["PositionProfitByTrade"] = pInvestorPositionDetail.PositionProfitByTrade
# ///投资者保证金
l_dict["Margin"] = pInvestorPositionDetail.Margin
# ///交易所保证金
l_dict["ExchMargin"] = pInvestorPositionDetail.ExchMargin
# ///保证金率
l_dict["MarginRateByMoney"] = pInvestorPositionDetail.MarginRateByMoney
# ///保证金率(按手数)
l_dict["MarginRateByVolume"] = pInvestorPositionDetail.MarginRateByVolume
# ///昨结算价
l_dict["LastSettlementPrice"] = pInvestorPositionDetail.LastSettlementPrice
# ///结算价
l_dict["SettlementPrice"] = pInvestorPositionDetail.SettlementPrice
# ///平仓量
l_dict["CloseVolume"] = pInvestorPositionDetail.CloseVolume
# ///平仓金额
l_dict["CloseAmount"] = pInvestorPositionDetail.CloseAmount
# ///投资单元代码
l_dict["InvestUnitID"] = pInvestorPositionDetail.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryNotice(self, pNotice, pRspInfo, nRequestID, bIsLast):
'''
///请求查询客户通知响应
'''
if bIsLast == True:
self.req_call['QryNotice'] = 1
self.PTP_Algos.DumpRspDict("T_Notice",pNotice)
l_dict={}
"""CThostFtdcNoticeField
# ///经纪公司代码
l_dict["BrokerID"] = pNotice.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///消息正文
l_dict["Content"] = pNotice.Content.decode(encoding="gb18030", errors="ignore")
# ///经纪公司通知内容序列号
l_dict["SequenceLabel"] = pNotice.SequenceLabel.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQrySettlementInfoConfirm(self, pSettlementInfoConfirm, pRspInfo, nRequestID, bIsLast):
'''
///请求查询结算信息确认响应
'''
if bIsLast == True:
self.req_call['QrySettlementInfoConfirm'] = 1
self.PTP_Algos.DumpRspDict("T_SettlementInfoConfirm",pSettlementInfoConfirm)
l_dict={}
"""CThostFtdcSettlementInfoConfirmField
# ///经纪公司代码
l_dict["BrokerID"] = pSettlementInfoConfirm.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pSettlementInfoConfirm.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///确认日期
l_dict["ConfirmDate"] = pSettlementInfoConfirm.ConfirmDate.decode(encoding="gb18030", errors="ignore")
# ///确认时间
l_dict["ConfirmTime"] = pSettlementInfoConfirm.ConfirmTime.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pSettlementInfoConfirm.SettlementID
# ///投资者帐号
l_dict["AccountID"] = pSettlementInfoConfirm.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pSettlementInfoConfirm.CurrencyID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryInvestorPositionCombineDetail(self, pInvestorPositionCombineDetail, pRspInfo, nRequestID, bIsLast):
'''
///请求查询投资者持仓明细响应
'''
if bIsLast == True:
self.req_call['QryInvestorPositionCombineDetail'] = 1
self.PTP_Algos.DumpRspDict("T_InvestorPositionCombineDetail",pInvestorPositionCombineDetail)
l_dict={}
"""CThostFtdcInvestorPositionCombineDetailField
# ///交易日
l_dict["TradingDay"] = pInvestorPositionCombineDetail.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///开仓日期
l_dict["OpenDate"] = pInvestorPositionCombineDetail.OpenDate.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pInvestorPositionCombineDetail.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pInvestorPositionCombineDetail.SettlementID
# ///经纪公司代码
l_dict["BrokerID"] = pInvestorPositionCombineDetail.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInvestorPositionCombineDetail.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///组合编号
l_dict["ComTradeID"] = pInvestorPositionCombineDetail.ComTradeID.decode(encoding="gb18030", errors="ignore")
# ///撮合编号
l_dict["TradeID"] = pInvestorPositionCombineDetail.TradeID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pInvestorPositionCombineDetail.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pInvestorPositionCombineDetail.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///买卖
l_dict["Direction"] = pInvestorPositionCombineDetail.Direction.decode(encoding="gb18030", errors="ignore")
# ///持仓量
l_dict["TotalAmt"] = pInvestorPositionCombineDetail.TotalAmt
# ///投资者保证金
l_dict["Margin"] = pInvestorPositionCombineDetail.Margin
# ///交易所保证金
l_dict["ExchMargin"] = pInvestorPositionCombineDetail.ExchMargin
# ///保证金率
l_dict["MarginRateByMoney"] = pInvestorPositionCombineDetail.MarginRateByMoney
# ///保证金率(按手数)
l_dict["MarginRateByVolume"] = pInvestorPositionCombineDetail.MarginRateByVolume
# ///单腿编号
l_dict["LegID"] = pInvestorPositionCombineDetail.LegID
# ///单腿乘数
l_dict["LegMultiple"] = pInvestorPositionCombineDetail.LegMultiple
# ///组合持仓合约编码
l_dict["CombInstrumentID"] = pInvestorPositionCombineDetail.CombInstrumentID.decode(encoding="gb18030", errors="ignore")
# ///成交组号
l_dict["TradeGroupID"] = pInvestorPositionCombineDetail.TradeGroupID
# ///投资单元代码
l_dict["InvestUnitID"] = pInvestorPositionCombineDetail.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryCFMMCTradingAccountKey(self, pCFMMCTradingAccountKey, pRspInfo, nRequestID, bIsLast):
'''
///查询保证金监管系统经纪公司资金账户密钥响应
'''
if bIsLast == True:
self.req_call['QryCFMMCTradingAccountKey'] = 1
self.PTP_Algos.DumpRspDict("T_CFMMCTradingAccountKey",pCFMMCTradingAccountKey)
l_dict={}
"""CThostFtdcCFMMCTradingAccountKeyField
# ///经纪公司代码
l_dict["BrokerID"] = pCFMMCTradingAccountKey.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///经纪公司统一编码
l_dict["ParticipantID"] = pCFMMCTradingAccountKey.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pCFMMCTradingAccountKey.AccountID.decode(encoding="gb18030", errors="ignore")
# ///密钥编号
l_dict["KeyID"] = pCFMMCTradingAccountKey.KeyID
# ///动态密钥
l_dict["CurrentKey"] = pCFMMCTradingAccountKey.CurrentKey.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryEWarrantOffset(self, pEWarrantOffset, pRspInfo, nRequestID, bIsLast):
'''
///请求查询仓单折抵信息响应
'''
if bIsLast == True:
self.req_call['QryEWarrantOffset'] = 1
self.PTP_Algos.DumpRspDict("T_EWarrantOffset",pEWarrantOffset)
l_dict={}
"""CThostFtdcEWarrantOffsetField
# ///交易日期
l_dict["TradingDay"] = pEWarrantOffset.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///经纪公司代码
l_dict["BrokerID"] = pEWarrantOffset.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pEWarrantOffset.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pEWarrantOffset.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pEWarrantOffset.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///买卖方向
l_dict["Direction"] = pEWarrantOffset.Direction.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pEWarrantOffset.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///数量
l_dict["Volume"] = pEWarrantOffset.Volume
# ///投资单元代码
l_dict["InvestUnitID"] = pEWarrantOffset.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryInvestorProductGroupMargin(self, pInvestorProductGroupMargin, pRspInfo, nRequestID, bIsLast):
'''
///请求查询投资者品种/跨品种保证金响应
'''
if bIsLast == True:
self.req_call['QryInvestorProductGroupMargin'] = 1
self.PTP_Algos.DumpRspDict("T_InvestorProductGroupMargin",pInvestorProductGroupMargin)
l_dict={}
"""CThostFtdcInvestorProductGroupMarginField
# ///品种/跨品种标示
l_dict["ProductGroupID"] = pInvestorProductGroupMargin.ProductGroupID.decode(encoding="gb18030", errors="ignore")
# ///经纪公司代码
l_dict["BrokerID"] = pInvestorProductGroupMargin.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInvestorProductGroupMargin.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///交易日
l_dict["TradingDay"] = pInvestorProductGroupMargin.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pInvestorProductGroupMargin.SettlementID
# ///冻结的保证金
l_dict["FrozenMargin"] = pInvestorProductGroupMargin.FrozenMargin
# ///多头冻结的保证金
l_dict["LongFrozenMargin"] = pInvestorProductGroupMargin.LongFrozenMargin
# ///空头冻结的保证金
l_dict["ShortFrozenMargin"] = pInvestorProductGroupMargin.ShortFrozenMargin
# ///占用的保证金
l_dict["UseMargin"] = pInvestorProductGroupMargin.UseMargin
# ///多头保证金
l_dict["LongUseMargin"] = pInvestorProductGroupMargin.LongUseMargin
# ///空头保证金
l_dict["ShortUseMargin"] = pInvestorProductGroupMargin.ShortUseMargin
# ///交易所保证金
l_dict["ExchMargin"] = pInvestorProductGroupMargin.ExchMargin
# ///交易所多头保证金
l_dict["LongExchMargin"] = pInvestorProductGroupMargin.LongExchMargin
# ///交易所空头保证金
l_dict["ShortExchMargin"] = pInvestorProductGroupMargin.ShortExchMargin
# ///平仓盈亏
l_dict["CloseProfit"] = pInvestorProductGroupMargin.CloseProfit
# ///冻结的手续费
l_dict["FrozenCommission"] = pInvestorProductGroupMargin.FrozenCommission
# ///手续费
l_dict["Commission"] = pInvestorProductGroupMargin.Commission
# ///冻结的资金
l_dict["FrozenCash"] = pInvestorProductGroupMargin.FrozenCash
# ///资金差额
l_dict["CashIn"] = pInvestorProductGroupMargin.CashIn
# ///持仓盈亏
l_dict["PositionProfit"] = pInvestorProductGroupMargin.PositionProfit
# ///折抵总金额
l_dict["OffsetAmount"] = pInvestorProductGroupMargin.OffsetAmount
# ///多头折抵总金额
l_dict["LongOffsetAmount"] = pInvestorProductGroupMargin.LongOffsetAmount
# ///空头折抵总金额
l_dict["ShortOffsetAmount"] = pInvestorProductGroupMargin.ShortOffsetAmount
# ///交易所折抵总金额
l_dict["ExchOffsetAmount"] = pInvestorProductGroupMargin.ExchOffsetAmount
# ///交易所多头折抵总金额
l_dict["LongExchOffsetAmount"] = pInvestorProductGroupMargin.LongExchOffsetAmount
# ///交易所空头折抵总金额
l_dict["ShortExchOffsetAmount"] = pInvestorProductGroupMargin.ShortExchOffsetAmount
# ///投机套保标志
l_dict["HedgeFlag"] = pInvestorProductGroupMargin.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pInvestorProductGroupMargin.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInvestorProductGroupMargin.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryExchangeMarginRate(self, pExchangeMarginRate, pRspInfo, nRequestID, bIsLast):
'''
///请求查询交易所保证金率响应
'''
if bIsLast == True:
self.req_call['QryExchangeMarginRate'] = 1
self.PTP_Algos.DumpRspDict("T_ExchangeMarginRate",pExchangeMarginRate)
l_dict={}
"""CThostFtdcExchangeMarginRateField
# ///经纪公司代码
l_dict["BrokerID"] = pExchangeMarginRate.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pExchangeMarginRate.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pExchangeMarginRate.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///多头保证金率
l_dict["LongMarginRatioByMoney"] = pExchangeMarginRate.LongMarginRatioByMoney
# ///多头保证金费
l_dict["LongMarginRatioByVolume"] = pExchangeMarginRate.LongMarginRatioByVolume
# ///空头保证金率
l_dict["ShortMarginRatioByMoney"] = pExchangeMarginRate.ShortMarginRatioByMoney
# ///空头保证金费
l_dict["ShortMarginRatioByVolume"] = pExchangeMarginRate.ShortMarginRatioByVolume
# ///交易所代码
l_dict["ExchangeID"] = pExchangeMarginRate.ExchangeID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryExchangeMarginRateAdjust(self, pExchangeMarginRateAdjust, pRspInfo, nRequestID, bIsLast):
'''
///请求查询交易所调整保证金率响应
'''
if bIsLast == True:
self.req_call['QryExchangeMarginRateAdjust'] = 1
self.PTP_Algos.DumpRspDict("T_ExchangeMarginRateAdjust",pExchangeMarginRateAdjust)
l_dict={}
"""CThostFtdcExchangeMarginRateAdjustField
# ///经纪公司代码
l_dict["BrokerID"] = pExchangeMarginRateAdjust.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pExchangeMarginRateAdjust.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pExchangeMarginRateAdjust.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///跟随交易所投资者多头保证金率
l_dict["LongMarginRatioByMoney"] = pExchangeMarginRateAdjust.LongMarginRatioByMoney
# ///跟随交易所投资者多头保证金费
l_dict["LongMarginRatioByVolume"] = pExchangeMarginRateAdjust.LongMarginRatioByVolume
# ///跟随交易所投资者空头保证金率
l_dict["ShortMarginRatioByMoney"] = pExchangeMarginRateAdjust.ShortMarginRatioByMoney
# ///跟随交易所投资者空头保证金费
l_dict["ShortMarginRatioByVolume"] = pExchangeMarginRateAdjust.ShortMarginRatioByVolume
# ///交易所多头保证金率
l_dict["ExchLongMarginRatioByMoney" = pExchangeMarginRateAdjust.ExchLongMarginRatioByMoney
# ///交易所多头保证金费
l_dict["ExchLongMarginRatioByVolume = pExchangeMarginRateAdjust.ExchLongMarginRatioByVolume
# ///交易所空头保证金率
l_dict["ExchShortMarginRatioByMoney = pExchangeMarginRateAdjust.ExchShortMarginRatioByMoney
# ///交易所空头保证金费
l_dict["ExchShortMarginRatioByVolum = pExchangeMarginRateAdjust.ExchShortMarginRatioByVolume
# ///不跟随交易所投资者多头保证金率
l_dict["NoLongMarginRatioByMoney"] = pExchangeMarginRateAdjust.NoLongMarginRatioByMoney
# ///不跟随交易所投资者多头保证金费
l_dict["NoLongMarginRatioByVolume"] = pExchangeMarginRateAdjust.NoLongMarginRatioByVolume
# ///不跟随交易所投资者空头保证金率
l_dict["NoShortMarginRatioByMoney"] = pExchangeMarginRateAdjust.NoShortMarginRatioByMoney
# ///不跟随交易所投资者空头保证金费
l_dict["NoShortMarginRatioByVolume" = pExchangeMarginRateAdjust.NoShortMarginRatioByVolume
#"""
def OnRspQryExchangeRate(self, pExchangeRate, pRspInfo, nRequestID, bIsLast):
'''
///请求查询汇率响应
'''
if bIsLast == True:
self.req_call['QryExchangeRate'] = 1
self.PTP_Algos.DumpRspDict("T_ExchangeRate",pExchangeRate)
l_dict={}
"""CThostFtdcExchangeRateField
# ///经纪公司代码
l_dict["BrokerID"] = pExchangeRate.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///源币种
l_dict["FromCurrencyID"] = pExchangeRate.FromCurrencyID.decode(encoding="gb18030", errors="ignore")
# ///源币种单位数量
l_dict["FromCurrencyUnit"] = pExchangeRate.FromCurrencyUnit
# ///目标币种
l_dict["ToCurrencyID"] = pExchangeRate.ToCurrencyID.decode(encoding="gb18030", errors="ignore")
# ///汇率
l_dict["ExchangeRate"] = pExchangeRate.ExchangeRate
#"""
def OnRspQrySecAgentACIDMap(self, pSecAgentACIDMap, pRspInfo, nRequestID, bIsLast):
'''
///请求查询二级代理操作员银期权限响应
'''
if bIsLast == True:
self.req_call['QrySecAgentACIDMap'] = 1
self.PTP_Algos.DumpRspDict("T_SecAgentACIDMap",pSecAgentACIDMap)
l_dict={}
"""CThostFtdcSecAgentACIDMapField
# ///经纪公司代码
l_dict["BrokerID"] = pSecAgentACIDMap.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pSecAgentACIDMap.UserID.decode(encoding="gb18030", errors="ignore")
# ///资金账户
l_dict["AccountID"] = pSecAgentACIDMap.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种
l_dict["CurrencyID"] = pSecAgentACIDMap.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///境外中介机构资金帐号
l_dict["BrokerSecAgentID"] = pSecAgentACIDMap.BrokerSecAgentID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryProductExchRate(self, pProductExchRate, pRspInfo, nRequestID, bIsLast):
'''
///请求查询产品报价汇率
'''
if bIsLast == True:
self.req_call['QryProductExchRate'] = 1
self.PTP_Algos.DumpRspDict("T_ProductExchRate",pProductExchRate)
l_dict={}
"""CThostFtdcProductExchRateField
# ///产品代码
l_dict["ProductID"] = pProductExchRate.ProductID.decode(encoding="gb18030", errors="ignore")
# ///报价币种类型
l_dict["QuoteCurrencyID"] = pProductExchRate.QuoteCurrencyID.decode(encoding="gb18030", errors="ignore")
# ///汇率
l_dict["ExchangeRate"] = pProductExchRate.ExchangeRate
# ///交易所代码
l_dict["ExchangeID"] = pProductExchRate.ExchangeID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryProductGroup(self, pProductGroup, pRspInfo, nRequestID, bIsLast):
'''
///请求查询产品组
'''
if bIsLast == True:
self.req_call['QryProductGroup'] = 1
self.PTP_Algos.DumpRspDict("T_ProductGroup",pProductGroup)
l_dict={}
"""CThostFtdcProductGroupField
# ///产品代码
l_dict["ProductID"] = pProductGroup.ProductID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pProductGroup.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///产品组代码
l_dict["ProductGroupID"] = pProductGroup.ProductGroupID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryMMInstrumentCommissionRate(self, pMMInstrumentCommissionRate, pRspInfo, nRequestID, bIsLast):
'''
///请求查询做市商合约手续费率响应
'''
if bIsLast == True:
self.req_call['QryMMInstrumentCommissionRate'] = 1
self.PTP_Algos.DumpRspDict("T_MMInstrumentCommissionRate",pMMInstrumentCommissionRate)
l_dict={}
"""CThostFtdcMMInstrumentCommissionRateField
# ///合约代码
l_dict["InstrumentID"] = pMMInstrumentCommissionRate.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///投资者范围
l_dict["InvestorRange"] = pMMInstrumentCommissionRate.InvestorRange.decode(encoding="gb18030", errors="ignore")
# ///经纪公司代码
l_dict["BrokerID"] = pMMInstrumentCommissionRate.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pMMInstrumentCommissionRate.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///开仓手续费率
l_dict["OpenRatioByMoney"] = pMMInstrumentCommissionRate.OpenRatioByMoney
# ///开仓手续费
l_dict["OpenRatioByVolume"] = pMMInstrumentCommissionRate.OpenRatioByVolume
# ///平仓手续费率
l_dict["CloseRatioByMoney"] = pMMInstrumentCommissionRate.CloseRatioByMoney
# ///平仓手续费
l_dict["CloseRatioByVolume"] = pMMInstrumentCommissionRate.CloseRatioByVolume
# ///平今手续费率
l_dict["CloseTodayRatioByMoney"] = pMMInstrumentCommissionRate.CloseTodayRatioByMoney
# ///平今手续费
l_dict["CloseTodayRatioByVolume"] = pMMInstrumentCommissionRate.CloseTodayRatioByVolume
#"""
def OnRspQryMMOptionInstrCommRate(self, pMMOptionInstrCommRate, pRspInfo, nRequestID, bIsLast):
'''
///请求查询做市商期权合约手续费响应
'''
if bIsLast == True:
self.req_call['QryMMOptionInstrCommRate'] = 1
self.PTP_Algos.DumpRspDict("T_MMOptionInstrCommRate",pMMOptionInstrCommRate)
l_dict={}
"""CThostFtdcMMOptionInstrCommRateField
# ///合约代码
l_dict["InstrumentID"] = pMMOptionInstrCommRate.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///投资者范围
l_dict["InvestorRange"] = pMMOptionInstrCommRate.InvestorRange.decode(encoding="gb18030", errors="ignore")
# ///经纪公司代码
l_dict["BrokerID"] = pMMOptionInstrCommRate.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pMMOptionInstrCommRate.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///开仓手续费率
l_dict["OpenRatioByMoney"] = pMMOptionInstrCommRate.OpenRatioByMoney
# ///开仓手续费
l_dict["OpenRatioByVolume"] = pMMOptionInstrCommRate.OpenRatioByVolume
# ///平仓手续费率
l_dict["CloseRatioByMoney"] = pMMOptionInstrCommRate.CloseRatioByMoney
# ///平仓手续费
l_dict["CloseRatioByVolume"] = pMMOptionInstrCommRate.CloseRatioByVolume
# ///平今手续费率
l_dict["CloseTodayRatioByMoney"] = pMMOptionInstrCommRate.CloseTodayRatioByMoney
# ///平今手续费
l_dict["CloseTodayRatioByVolume"] = pMMOptionInstrCommRate.CloseTodayRatioByVolume
# ///执行手续费率
l_dict["StrikeRatioByMoney"] = pMMOptionInstrCommRate.StrikeRatioByMoney
# ///执行手续费
l_dict["StrikeRatioByVolume"] = pMMOptionInstrCommRate.StrikeRatioByVolume
#"""
def OnRspQryInstrumentOrderCommRate(self, pInstrumentOrderCommRate, pRspInfo, nRequestID, bIsLast):
'''
///请求查询报单手续费响应
'''
if bIsLast == True:
self.req_call['QryInstrumentOrderCommRate'] = 1
self.PTP_Algos.DumpRspDict("T_InstrumentOrderCommRate",pInstrumentOrderCommRate)
l_dict={}
"""CThostFtdcInstrumentOrderCommRateField
# ///合约代码
l_dict["InstrumentID"] = pInstrumentOrderCommRate.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///投资者范围
l_dict["InvestorRange"] = pInstrumentOrderCommRate.InvestorRange.decode(encoding="gb18030", errors="ignore")
# ///经纪公司代码
l_dict["BrokerID"] = pInstrumentOrderCommRate.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInstrumentOrderCommRate.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pInstrumentOrderCommRate.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///报单手续费
l_dict["OrderCommByVolume"] = pInstrumentOrderCommRate.OrderCommByVolume
# ///撤单手续费
l_dict["OrderActionCommByVolume"] = pInstrumentOrderCommRate.OrderActionCommByVolume
# ///交易所代码
l_dict["ExchangeID"] = pInstrumentOrderCommRate.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInstrumentOrderCommRate.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQrySecAgentTradingAccount(self, pTradingAccount, pRspInfo, nRequestID, bIsLast):
'''
///请求查询资金账户响应
'''
if bIsLast == True:
self.req_call['QrySecAgentTradingAccount'] = 1
self.PTP_Algos.DumpRspDict("T_TradingAccount",pTradingAccount)
l_dict={}
"""CThostFtdcTradingAccountField
# ///经纪公司代码
l_dict["BrokerID"] = pTradingAccount.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pTradingAccount.AccountID.decode(encoding="gb18030", errors="ignore")
# ///上次质押金额
l_dict["PreMortgage"] = pTradingAccount.PreMortgage
# ///上次信用额度
l_dict["PreCredit"] = pTradingAccount.PreCredit
# ///上次存款额
l_dict["PreDeposit"] = pTradingAccount.PreDeposit
# ///上次结算准备金
l_dict["PreBalance"] = pTradingAccount.PreBalance
# ///上次占用的保证金
l_dict["PreMargin"] = pTradingAccount.PreMargin
# ///利息基数
l_dict["InterestBase"] = pTradingAccount.InterestBase
# ///利息收入
l_dict["Interest"] = pTradingAccount.Interest
# ///入金金额
l_dict["Deposit"] = pTradingAccount.Deposit
# ///出金金额
l_dict["Withdraw"] = pTradingAccount.Withdraw
# ///冻结的保证金
l_dict["FrozenMargin"] = pTradingAccount.FrozenMargin
# ///冻结的资金
l_dict["FrozenCash"] = pTradingAccount.FrozenCash
# ///冻结的手续费
l_dict["FrozenCommission"] = pTradingAccount.FrozenCommission
# ///当前保证金总额
l_dict["CurrMargin"] = pTradingAccount.CurrMargin
# ///资金差额
l_dict["CashIn"] = pTradingAccount.CashIn
# ///手续费
l_dict["Commission"] = pTradingAccount.Commission
# ///平仓盈亏
l_dict["CloseProfit"] = pTradingAccount.CloseProfit
# ///持仓盈亏
l_dict["PositionProfit"] = pTradingAccount.PositionProfit
# ///期货结算准备金
l_dict["Balance"] = pTradingAccount.Balance
# ///可用资金
l_dict["Available"] = pTradingAccount.Available
# ///可取资金
l_dict["WithdrawQuota"] = pTradingAccount.WithdrawQuota
# ///基本准备金
l_dict["Reserve"] = pTradingAccount.Reserve
# ///交易日
l_dict["TradingDay"] = pTradingAccount.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pTradingAccount.SettlementID
# ///信用额度
l_dict["Credit"] = pTradingAccount.Credit
# ///质押金额
l_dict["Mortgage"] = pTradingAccount.Mortgage
# ///交易所保证金
l_dict["ExchangeMargin"] = pTradingAccount.ExchangeMargin
# ///投资者交割保证金
l_dict["DeliveryMargin"] = pTradingAccount.DeliveryMargin
# ///交易所交割保证金
l_dict["ExchangeDeliveryMargin"] = pTradingAccount.ExchangeDeliveryMargin
# ///保底期货结算准备金
l_dict["ReserveBalance"] = pTradingAccount.ReserveBalance
# ///币种代码
l_dict["CurrencyID"] = pTradingAccount.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///上次货币质入金额
l_dict["PreFundMortgageIn"] = pTradingAccount.PreFundMortgageIn
# ///上次货币质出金额
l_dict["PreFundMortgageOut"] = pTradingAccount.PreFundMortgageOut
# ///货币质入金额
l_dict["FundMortgageIn"] = pTradingAccount.FundMortgageIn
# ///货币质出金额
l_dict["FundMortgageOut"] = pTradingAccount.FundMortgageOut
# ///货币质押余额
l_dict["FundMortgageAvailable"] = pTradingAccount.FundMortgageAvailable
# ///可质押货币金额
l_dict["MortgageableFund"] = pTradingAccount.MortgageableFund
# ///特殊产品占用保证金
l_dict["SpecProductMargin"] = pTradingAccount.SpecProductMargin
# ///特殊产品冻结保证金
l_dict["SpecProductFrozenMargin"] = pTradingAccount.SpecProductFrozenMargin
# ///特殊产品手续费
l_dict["SpecProductCommission"] = pTradingAccount.SpecProductCommission
# ///特殊产品冻结手续费
l_dict["SpecProductFrozenCommission = pTradingAccount.SpecProductFrozenCommission
# ///特殊产品持仓盈亏
l_dict["SpecProductPositionProfit"] = pTradingAccount.SpecProductPositionProfit
# ///特殊产品平仓盈亏
l_dict["SpecProductCloseProfit"] = pTradingAccount.SpecProductCloseProfit
# ///根据持仓盈亏算法计算的特殊产品持仓盈亏
l_dict["SpecProductPositionProfitBy = pTradingAccount.SpecProductPositionProfitByAlg
# ///特殊产品交易所保证金
l_dict["SpecProductExchangeMargin"] = pTradingAccount.SpecProductExchangeMargin
# ///业务类型
l_dict["BizType"] = pTradingAccount.BizType.decode(encoding="gb18030", errors="ignore")
# ///延时换汇冻结金额
l_dict["FrozenSwap"] = pTradingAccount.FrozenSwap
# ///剩余换汇额度
l_dict["RemainSwap"] = pTradingAccount.RemainSwap
#"""
def OnRspQrySecAgentCheckMode(self, pSecAgentCheckMode, pRspInfo, nRequestID, bIsLast):
'''
///请求查询二级代理商资金校验模式响应
'''
if bIsLast == True:
self.req_call['QrySecAgentCheckMode'] = 1
self.PTP_Algos.DumpRspDict("T_SecAgentCheckMode",pSecAgentCheckMode)
l_dict={}
"""CThostFtdcSecAgentCheckModeField
# ///投资者代码
l_dict["InvestorID"] = pSecAgentCheckMode.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///经纪公司代码
l_dict["BrokerID"] = pSecAgentCheckMode.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///币种
l_dict["CurrencyID"] = pSecAgentCheckMode.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///境外中介机构资金帐号
l_dict["BrokerSecAgentID"] = pSecAgentCheckMode.BrokerSecAgentID.decode(encoding="gb18030", errors="ignore")
# ///是否需要校验自己的资金账户
l_dict["CheckSelfAccount"] = pSecAgentCheckMode.CheckSelfAccount
#"""
def OnRspQryOptionInstrTradeCost(self, pOptionInstrTradeCost, pRspInfo, nRequestID, bIsLast):
'''
///请求查询期权交易成本响应
'''
if bIsLast == True:
self.req_call['QryOptionInstrTradeCost'] = 1
self.PTP_Algos.DumpRspDict("T_OptionInstrTradeCost",pOptionInstrTradeCost)
l_dict={}
"""CThostFtdcOptionInstrTradeCostField
# ///经纪公司代码
l_dict["BrokerID"] = pOptionInstrTradeCost.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pOptionInstrTradeCost.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pOptionInstrTradeCost.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pOptionInstrTradeCost.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///期权合约保证金不变部分
l_dict["FixedMargin"] = pOptionInstrTradeCost.FixedMargin
# ///期权合约最小保证金
l_dict["MiniMargin"] = pOptionInstrTradeCost.MiniMargin
# ///期权合约权利金
l_dict["Royalty"] = pOptionInstrTradeCost.Royalty
# ///交易所期权合约保证金不变部分
l_dict["ExchFixedMargin"] = pOptionInstrTradeCost.ExchFixedMargin
# ///交易所期权合约最小保证金
l_dict["ExchMiniMargin"] = pOptionInstrTradeCost.ExchMiniMargin
# ///交易所代码
l_dict["ExchangeID"] = pOptionInstrTradeCost.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pOptionInstrTradeCost.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryOptionInstrCommRate(self, pOptionInstrCommRate, pRspInfo, nRequestID, bIsLast):
'''
///请求查询期权合约手续费响应
'''
if bIsLast == True:
self.req_call['QryOptionInstrCommRate'] = 1
self.PTP_Algos.DumpRspDict("T_OptionInstrCommRate",pOptionInstrCommRate)
l_dict={}
"""CThostFtdcOptionInstrCommRateField
# ///合约代码
l_dict["InstrumentID"] = pOptionInstrCommRate.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///投资者范围
l_dict["InvestorRange"] = pOptionInstrCommRate.InvestorRange.decode(encoding="gb18030", errors="ignore")
# ///经纪公司代码
l_dict["BrokerID"] = pOptionInstrCommRate.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pOptionInstrCommRate.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///开仓手续费率
l_dict["OpenRatioByMoney"] = pOptionInstrCommRate.OpenRatioByMoney
# ///开仓手续费
l_dict["OpenRatioByVolume"] = pOptionInstrCommRate.OpenRatioByVolume
# ///平仓手续费率
l_dict["CloseRatioByMoney"] = pOptionInstrCommRate.CloseRatioByMoney
# ///平仓手续费
l_dict["CloseRatioByVolume"] = pOptionInstrCommRate.CloseRatioByVolume
# ///平今手续费率
l_dict["CloseTodayRatioByMoney"] = pOptionInstrCommRate.CloseTodayRatioByMoney
# ///平今手续费
l_dict["CloseTodayRatioByVolume"] = pOptionInstrCommRate.CloseTodayRatioByVolume
# ///执行手续费率
l_dict["StrikeRatioByMoney"] = pOptionInstrCommRate.StrikeRatioByMoney
# ///执行手续费
l_dict["StrikeRatioByVolume"] = pOptionInstrCommRate.StrikeRatioByVolume
# ///交易所代码
l_dict["ExchangeID"] = pOptionInstrCommRate.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pOptionInstrCommRate.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryExecOrder(self, pExecOrder, pRspInfo, nRequestID, bIsLast):
'''
///请求查询执行宣告响应
'''
if bIsLast == True:
self.req_call['QryExecOrder'] = 1
self.PTP_Algos.DumpRspDict("T_ExecOrder",pExecOrder)
l_dict={}
"""CThostFtdcExecOrderField
# ///经纪公司代码
l_dict["BrokerID"] = pExecOrder.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pExecOrder.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pExecOrder.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///执行宣告引用
l_dict["ExecOrderRef"] = pExecOrder.ExecOrderRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pExecOrder.UserID.decode(encoding="gb18030", errors="ignore")
# ///数量
l_dict["Volume"] = pExecOrder.Volume
# ///请求编号
l_dict["RequestID"] = pExecOrder.RequestID
# ///业务单元
l_dict["BusinessUnit"] = pExecOrder.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///开平标志
l_dict["OffsetFlag"] = pExecOrder.OffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pExecOrder.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///执行类型
l_dict["ActionType"] = pExecOrder.ActionType.decode(encoding="gb18030", errors="ignore")
# ///保留头寸申请的持仓方向
l_dict["PosiDirection"] = pExecOrder.PosiDirection.decode(encoding="gb18030", errors="ignore")
# ///期权行权后是否保留期货头寸的标记,该字段已废弃
l_dict["ReservePositionFlag"] = pExecOrder.ReservePositionFlag.decode(encoding="gb18030", errors="ignore")
# ///期权行权后生成的头寸是否自动平仓
l_dict["CloseFlag"] = pExecOrder.CloseFlag.decode(encoding="gb18030", errors="ignore")
# ///本地执行宣告编号
l_dict["ExecOrderLocalID"] = pExecOrder.ExecOrderLocalID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pExecOrder.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pExecOrder.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pExecOrder.ClientID.decode(encoding="gb18030", errors="ignore")
# ///合约在交易所的代码
l_dict["ExchangeInstID"] = pExecOrder.ExchangeInstID.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pExecOrder.TraderID.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pExecOrder.InstallID
# ///执行宣告提交状态
l_dict["OrderSubmitStatus"] = pExecOrder.OrderSubmitStatus.decode(encoding="gb18030", errors="ignore")
# ///报单提示序号
l_dict["NotifySequence"] = pExecOrder.NotifySequence
# ///交易日
l_dict["TradingDay"] = pExecOrder.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pExecOrder.SettlementID
# ///执行宣告编号
l_dict["ExecOrderSysID"] = pExecOrder.ExecOrderSysID.decode(encoding="gb18030", errors="ignore")
# ///报单日期
l_dict["InsertDate"] = pExecOrder.InsertDate.decode(encoding="gb18030", errors="ignore")
# ///插入时间
l_dict["InsertTime"] = pExecOrder.InsertTime.decode(encoding="gb18030", errors="ignore")
# ///撤销时间
l_dict["CancelTime"] = pExecOrder.CancelTime.decode(encoding="gb18030", errors="ignore")
# ///执行结果
l_dict["ExecResult"] = pExecOrder.ExecResult.decode(encoding="gb18030", errors="ignore")
# ///结算会员编号
l_dict["ClearingPartID"] = pExecOrder.ClearingPartID.decode(encoding="gb18030", errors="ignore")
# ///序号
l_dict["SequenceNo"] = pExecOrder.SequenceNo
# ///前置编号
l_dict["FrontID"] = pExecOrder.FrontID
# ///会话编号
l_dict["SessionID"] = pExecOrder.SessionID
# ///用户端产品信息
l_dict["UserProductInfo"] = pExecOrder.UserProductInfo.decode(encoding="gb18030", errors="ignore")
# ///状态信息
l_dict["StatusMsg"] = pExecOrder.StatusMsg.decode(encoding="gb18030", errors="ignore")
# ///操作用户代码
l_dict["ActiveUserID"] = pExecOrder.ActiveUserID.decode(encoding="gb18030", errors="ignore")
# ///经纪公司报单编号
l_dict["BrokerExecOrderSeq"] = pExecOrder.BrokerExecOrderSeq
# ///营业部编号
l_dict["BranchID"] = pExecOrder.BranchID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pExecOrder.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///资金账号
l_dict["AccountID"] = pExecOrder.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pExecOrder.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pExecOrder.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pExecOrder.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryForQuote(self, pForQuote, pRspInfo, nRequestID, bIsLast):
'''
///请求查询询价响应
'''
if bIsLast == True:
self.req_call['QryForQuote'] = 1
self.PTP_Algos.DumpRspDict("T_ForQuote",pForQuote)
l_dict={}
"""CThostFtdcForQuoteField
# ///经纪公司代码
l_dict["BrokerID"] = pForQuote.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pForQuote.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pForQuote.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///询价引用
l_dict["ForQuoteRef"] = pForQuote.ForQuoteRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pForQuote.UserID.decode(encoding="gb18030", errors="ignore")
# ///本地询价编号
l_dict["ForQuoteLocalID"] = pForQuote.ForQuoteLocalID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pForQuote.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pForQuote.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pForQuote.ClientID.decode(encoding="gb18030", errors="ignore")
# ///合约在交易所的代码
l_dict["ExchangeInstID"] = pForQuote.ExchangeInstID.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pForQuote.TraderID.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pForQuote.InstallID
# ///报单日期
l_dict["InsertDate"] = pForQuote.InsertDate.decode(encoding="gb18030", errors="ignore")
# ///插入时间
l_dict["InsertTime"] = pForQuote.InsertTime.decode(encoding="gb18030", errors="ignore")
# ///询价状态
l_dict["ForQuoteStatus"] = pForQuote.ForQuoteStatus.decode(encoding="gb18030", errors="ignore")
# ///前置编号
l_dict["FrontID"] = pForQuote.FrontID
# ///会话编号
l_dict["SessionID"] = pForQuote.SessionID
# ///状态信息
l_dict["StatusMsg"] = pForQuote.StatusMsg.decode(encoding="gb18030", errors="ignore")
# ///操作用户代码
l_dict["ActiveUserID"] = pForQuote.ActiveUserID.decode(encoding="gb18030", errors="ignore")
# ///经纪公司询价编号
l_dict["BrokerForQutoSeq"] = pForQuote.BrokerForQutoSeq
# ///投资单元代码
l_dict["InvestUnitID"] = pForQuote.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pForQuote.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pForQuote.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryQuote(self, pQuote, pRspInfo, nRequestID, bIsLast):
'''
///请求查询报价响应
'''
if bIsLast == True:
self.req_call['QryQuote'] = 1
self.PTP_Algos.DumpRspDict("T_Quote",pQuote)
l_dict={}
"""CThostFtdcQuoteField
# ///经纪公司代码
l_dict["BrokerID"] = pQuote.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pQuote.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pQuote.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///报价引用
l_dict["QuoteRef"] = pQuote.QuoteRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pQuote.UserID.decode(encoding="gb18030", errors="ignore")
# ///卖价格
l_dict["AskPrice"] = pQuote.AskPrice
# ///买价格
l_dict["BidPrice"] = pQuote.BidPrice
# ///卖数量
l_dict["AskVolume"] = pQuote.AskVolume
# ///买数量
l_dict["BidVolume"] = pQuote.BidVolume
# ///请求编号
l_dict["RequestID"] = pQuote.RequestID
# ///业务单元
l_dict["BusinessUnit"] = pQuote.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///卖开平标志
l_dict["AskOffsetFlag"] = pQuote.AskOffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///买开平标志
l_dict["BidOffsetFlag"] = pQuote.BidOffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///卖投机套保标志
l_dict["AskHedgeFlag"] = pQuote.AskHedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///买投机套保标志
l_dict["BidHedgeFlag"] = pQuote.BidHedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///本地报价编号
l_dict["QuoteLocalID"] = pQuote.QuoteLocalID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pQuote.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pQuote.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pQuote.ClientID.decode(encoding="gb18030", errors="ignore")
# ///合约在交易所的代码
l_dict["ExchangeInstID"] = pQuote.ExchangeInstID.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pQuote.TraderID.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pQuote.InstallID
# ///报价提示序号
l_dict["NotifySequence"] = pQuote.NotifySequence
# ///报价提交状态
l_dict["OrderSubmitStatus"] = pQuote.OrderSubmitStatus.decode(encoding="gb18030", errors="ignore")
# ///交易日
l_dict["TradingDay"] = pQuote.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pQuote.SettlementID
# ///报价编号
l_dict["QuoteSysID"] = pQuote.QuoteSysID.decode(encoding="gb18030", errors="ignore")
# ///报单日期
l_dict["InsertDate"] = pQuote.InsertDate.decode(encoding="gb18030", errors="ignore")
# ///插入时间
l_dict["InsertTime"] = pQuote.InsertTime.decode(encoding="gb18030", errors="ignore")
# ///撤销时间
l_dict["CancelTime"] = pQuote.CancelTime.decode(encoding="gb18030", errors="ignore")
# ///报价状态
l_dict["QuoteStatus"] = pQuote.QuoteStatus.decode(encoding="gb18030", errors="ignore")
# ///结算会员编号
l_dict["ClearingPartID"] = pQuote.ClearingPartID.decode(encoding="gb18030", errors="ignore")
# ///序号
l_dict["SequenceNo"] = pQuote.SequenceNo
# ///卖方报单编号
l_dict["AskOrderSysID"] = pQuote.AskOrderSysID.decode(encoding="gb18030", errors="ignore")
# ///买方报单编号
l_dict["BidOrderSysID"] = pQuote.BidOrderSysID.decode(encoding="gb18030", errors="ignore")
# ///前置编号
l_dict["FrontID"] = pQuote.FrontID
# ///会话编号
l_dict["SessionID"] = pQuote.SessionID
# ///用户端产品信息
l_dict["UserProductInfo"] = pQuote.UserProductInfo.decode(encoding="gb18030", errors="ignore")
# ///状态信息
l_dict["StatusMsg"] = pQuote.StatusMsg.decode(encoding="gb18030", errors="ignore")
# ///操作用户代码
l_dict["ActiveUserID"] = pQuote.ActiveUserID.decode(encoding="gb18030", errors="ignore")
# ///经纪公司报价编号
l_dict["BrokerQuoteSeq"] = pQuote.BrokerQuoteSeq
# ///衍生卖报单引用
l_dict["AskOrderRef"] = pQuote.AskOrderRef.decode(encoding="gb18030", errors="ignore")
# ///衍生买报单引用
l_dict["BidOrderRef"] = pQuote.BidOrderRef.decode(encoding="gb18030", errors="ignore")
# ///应价编号
l_dict["ForQuoteSysID"] = pQuote.ForQuoteSysID.decode(encoding="gb18030", errors="ignore")
# ///营业部编号
l_dict["BranchID"] = pQuote.BranchID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pQuote.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///资金账号
l_dict["AccountID"] = pQuote.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pQuote.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pQuote.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pQuote.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryOptionSelfClose(self, pOptionSelfClose, pRspInfo, nRequestID, bIsLast):
'''
///请求查询期权自对冲响应
'''
if bIsLast == True:
self.req_call['QryOptionSelfClose'] = 1
self.PTP_Algos.DumpRspDict("T_OptionSelfClose",pOptionSelfClose)
l_dict={}
"""CThostFtdcOptionSelfCloseField
# ///经纪公司代码
l_dict["BrokerID"] = pOptionSelfClose.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pOptionSelfClose.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pOptionSelfClose.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///期权自对冲引用
l_dict["OptionSelfCloseRef"] = pOptionSelfClose.OptionSelfCloseRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pOptionSelfClose.UserID.decode(encoding="gb18030", errors="ignore")
# ///数量
l_dict["Volume"] = pOptionSelfClose.Volume
# ///请求编号
l_dict["RequestID"] = pOptionSelfClose.RequestID
# ///业务单元
l_dict["BusinessUnit"] = pOptionSelfClose.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pOptionSelfClose.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///期权行权的头寸是否自对冲
l_dict["OptSelfCloseFlag"] = pOptionSelfClose.OptSelfCloseFlag.decode(encoding="gb18030", errors="ignore")
# ///本地期权自对冲编号
l_dict["OptionSelfCloseLocalID"] = pOptionSelfClose.OptionSelfCloseLocalID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pOptionSelfClose.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pOptionSelfClose.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pOptionSelfClose.ClientID.decode(encoding="gb18030", errors="ignore")
# ///合约在交易所的代码
l_dict["ExchangeInstID"] = pOptionSelfClose.ExchangeInstID.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pOptionSelfClose.TraderID.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pOptionSelfClose.InstallID
# ///期权自对冲提交状态
l_dict["OrderSubmitStatus"] = pOptionSelfClose.OrderSubmitStatus.decode(encoding="gb18030", errors="ignore")
# ///报单提示序号
l_dict["NotifySequence"] = pOptionSelfClose.NotifySequence
# ///交易日
l_dict["TradingDay"] = pOptionSelfClose.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pOptionSelfClose.SettlementID
# ///期权自对冲编号
l_dict["OptionSelfCloseSysID"] = pOptionSelfClose.OptionSelfCloseSysID.decode(encoding="gb18030", errors="ignore")
# ///报单日期
l_dict["InsertDate"] = pOptionSelfClose.InsertDate.decode(encoding="gb18030", errors="ignore")
# ///插入时间
l_dict["InsertTime"] = pOptionSelfClose.InsertTime.decode(encoding="gb18030", errors="ignore")
# ///撤销时间
l_dict["CancelTime"] = pOptionSelfClose.CancelTime.decode(encoding="gb18030", errors="ignore")
# ///自对冲结果
l_dict["ExecResult"] = pOptionSelfClose.ExecResult.decode(encoding="gb18030", errors="ignore")
# ///结算会员编号
l_dict["ClearingPartID"] = pOptionSelfClose.ClearingPartID.decode(encoding="gb18030", errors="ignore")
# ///序号
l_dict["SequenceNo"] = pOptionSelfClose.SequenceNo
# ///前置编号
l_dict["FrontID"] = pOptionSelfClose.FrontID
# ///会话编号
l_dict["SessionID"] = pOptionSelfClose.SessionID
# ///用户端产品信息
l_dict["UserProductInfo"] = pOptionSelfClose.UserProductInfo.decode(encoding="gb18030", errors="ignore")
# ///状态信息
l_dict["StatusMsg"] = pOptionSelfClose.StatusMsg.decode(encoding="gb18030", errors="ignore")
# ///操作用户代码
l_dict["ActiveUserID"] = pOptionSelfClose.ActiveUserID.decode(encoding="gb18030", errors="ignore")
# ///经纪公司报单编号
l_dict["BrokerOptionSelfCloseSeq"] = pOptionSelfClose.BrokerOptionSelfCloseSeq
# ///营业部编号
l_dict["BranchID"] = pOptionSelfClose.BranchID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pOptionSelfClose.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///资金账号
l_dict["AccountID"] = pOptionSelfClose.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pOptionSelfClose.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pOptionSelfClose.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pOptionSelfClose.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryInvestUnit(self, pInvestUnit, pRspInfo, nRequestID, bIsLast):
'''
///请求查询投资单元响应
'''
if bIsLast == True:
self.req_call['QryInvestUnit'] = 1
self.PTP_Algos.DumpRspDict("T_InvestUnit",pInvestUnit)
l_dict={}
"""CThostFtdcInvestUnitField
# ///经纪公司代码
l_dict["BrokerID"] = pInvestUnit.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInvestUnit.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInvestUnit.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///投资者单元名称
l_dict["InvestorUnitName"] = pInvestUnit.InvestorUnitName.decode(encoding="gb18030", errors="ignore")
# ///投资者分组代码
l_dict["InvestorGroupID"] = pInvestUnit.InvestorGroupID.decode(encoding="gb18030", errors="ignore")
# ///手续费率模板代码
l_dict["CommModelID"] = pInvestUnit.CommModelID.decode(encoding="gb18030", errors="ignore")
# ///保证金率模板代码
l_dict["MarginModelID"] = pInvestUnit.MarginModelID.decode(encoding="gb18030", errors="ignore")
# ///资金账号
l_dict["AccountID"] = pInvestUnit.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pInvestUnit.CurrencyID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryCombInstrumentGuard(self, pCombInstrumentGuard, pRspInfo, nRequestID, bIsLast):
'''
///请求查询组合合约安全系数响应
'''
if bIsLast == True:
self.req_call['QryCombInstrumentGuard'] = 1
self.PTP_Algos.DumpRspDict("T_CombInstrumentGuard",pCombInstrumentGuard)
l_dict={}
"""CThostFtdcCombInstrumentGuardField
# ///经纪公司代码
l_dict["BrokerID"] = pCombInstrumentGuard.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pCombInstrumentGuard.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///
l_dict["GuarantRatio"] = pCombInstrumentGuard.GuarantRatio
# ///交易所代码
l_dict["ExchangeID"] = pCombInstrumentGuard.ExchangeID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryCombAction(self, pCombAction, pRspInfo, nRequestID, bIsLast):
'''
///请求查询申请组合响应
'''
if bIsLast == True:
self.req_call['QryCombAction'] = 1
self.PTP_Algos.DumpRspDict("T_CombAction",pCombAction)
l_dict={}
"""CThostFtdcCombActionField
# ///经纪公司代码
l_dict["BrokerID"] = pCombAction.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pCombAction.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pCombAction.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///组合引用
l_dict["CombActionRef"] = pCombAction.CombActionRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pCombAction.UserID.decode(encoding="gb18030", errors="ignore")
# ///买卖方向
l_dict["Direction"] = pCombAction.Direction.decode(encoding="gb18030", errors="ignore")
# ///数量
l_dict["Volume"] = pCombAction.Volume
# ///组合指令方向
l_dict["CombDirection"] = pCombAction.CombDirection.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pCombAction.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///本地申请组合编号
l_dict["ActionLocalID"] = pCombAction.ActionLocalID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pCombAction.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pCombAction.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pCombAction.ClientID.decode(encoding="gb18030", errors="ignore")
# ///合约在交易所的代码
l_dict["ExchangeInstID"] = pCombAction.ExchangeInstID.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pCombAction.TraderID.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pCombAction.InstallID
# ///组合状态
l_dict["ActionStatus"] = pCombAction.ActionStatus.decode(encoding="gb18030", errors="ignore")
# ///报单提示序号
l_dict["NotifySequence"] = pCombAction.NotifySequence
# ///交易日
l_dict["TradingDay"] = pCombAction.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pCombAction.SettlementID
# ///序号
l_dict["SequenceNo"] = pCombAction.SequenceNo
# ///前置编号
l_dict["FrontID"] = pCombAction.FrontID
# ///会话编号
l_dict["SessionID"] = pCombAction.SessionID
# ///用户端产品信息
l_dict["UserProductInfo"] = pCombAction.UserProductInfo.decode(encoding="gb18030", errors="ignore")
# ///状态信息
l_dict["StatusMsg"] = pCombAction.StatusMsg.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pCombAction.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pCombAction.MacAddress.decode(encoding="gb18030", errors="ignore")
# ///组合编号
l_dict["ComTradeID"] = pCombAction.ComTradeID.decode(encoding="gb18030", errors="ignore")
# ///营业部编号
l_dict["BranchID"] = pCombAction.BranchID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pCombAction.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryTransferSerial(self, pTransferSerial, pRspInfo, nRequestID, bIsLast):
'''
///请求查询转帐流水响应
'''
if bIsLast == True:
self.req_call['QryTransferSerial'] = 1
self.PTP_Algos.DumpRspDict("T_TransferSerial",pTransferSerial)
l_dict={}
"""CThostFtdcTransferSerialField
# ///平台流水号
l_dict["PlateSerial"] = pTransferSerial.PlateSerial
# ///交易发起方日期
l_dict["TradeDate"] = pTransferSerial.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradingDay"] = pTransferSerial.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pTransferSerial.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///交易代码
l_dict["TradeCode"] = pTransferSerial.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///会话编号
l_dict["SessionID"] = pTransferSerial.SessionID
# ///银行编码
l_dict["BankID"] = pTransferSerial.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构编码
l_dict["BankBranchID"] = pTransferSerial.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pTransferSerial.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pTransferSerial.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pTransferSerial.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///期货公司编码
l_dict["BrokerID"] = pTransferSerial.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pTransferSerial.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///期货公司帐号类型
l_dict["FutureAccType"] = pTransferSerial.FutureAccType.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pTransferSerial.AccountID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pTransferSerial.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///期货公司流水号
l_dict["FutureSerial"] = pTransferSerial.FutureSerial
# ///证件类型
l_dict["IdCardType"] = pTransferSerial.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pTransferSerial.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pTransferSerial.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///交易金额
l_dict["TradeAmount"] = pTransferSerial.TradeAmount
# ///应收客户费用
l_dict["CustFee"] = pTransferSerial.CustFee
# ///应收期货公司费用
l_dict["BrokerFee"] = pTransferSerial.BrokerFee
# ///有效标志
l_dict["AvailabilityFlag"] = pTransferSerial.AvailabilityFlag.decode(encoding="gb18030", errors="ignore")
# ///操作员
l_dict["OperatorCode"] = pTransferSerial.OperatorCode.decode(encoding="gb18030", errors="ignore")
# ///新银行帐号
l_dict["BankNewAccount"] = pTransferSerial.BankNewAccount.decode(encoding="gb18030", errors="ignore")
# ///错误代码
l_dict["ErrorID"] = pTransferSerial.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pTransferSerial.ErrorMsg.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryAccountregister(self, pAccountregister, pRspInfo, nRequestID, bIsLast):
'''
///请求查询银期签约关系响应
'''
if bIsLast == True:
self.req_call['QryAccountregister'] = 1
self.PTP_Algos.DumpRspDict("T_Accountregister",pAccountregister)
l_dict={}
"""CThostFtdcAccountregisterField
# ///交易日期
l_dict["TradeDay"] = pAccountregister.TradeDay.decode(encoding="gb18030", errors="ignore")
# ///银行编码
l_dict["BankID"] = pAccountregister.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构编码
l_dict["BankBranchID"] = pAccountregister.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pAccountregister.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///期货公司编码
l_dict["BrokerID"] = pAccountregister.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期货公司分支机构编码
l_dict["BrokerBranchID"] = pAccountregister.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pAccountregister.AccountID.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pAccountregister.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pAccountregister.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户姓名
l_dict["CustomerName"] = pAccountregister.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pAccountregister.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///开销户类别
l_dict["OpenOrDestroy"] = pAccountregister.OpenOrDestroy.decode(encoding="gb18030", errors="ignore")
# ///签约日期
l_dict["RegDate"] = pAccountregister.RegDate.decode(encoding="gb18030", errors="ignore")
# ///解约日期
l_dict["OutDate"] = pAccountregister.OutDate.decode(encoding="gb18030", errors="ignore")
# ///交易ID
l_dict["TID"] = pAccountregister.TID
# ///客户类型
l_dict["CustType"] = pAccountregister.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pAccountregister.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pAccountregister.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspError(self, pRspInfo, nRequestID, bIsLast):
'''
///错误应答
'''
if bIsLast == True:
self.req_call['Error'] = 1
self.PTP_Algos.DumpRspDict("T_RspInfo",pRspInfo)
l_dict={}
"""CThostFtdcRspInfoField
# ///错误代码
l_dict["ErrorID"] = pRspInfo.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pRspInfo.ErrorMsg.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnOrder(self, pOrder):
'''
///报单通知
'''
self.PTP_Algos.push_OnRtnOrder("T_Order",pOrder)
l_dict={}
"""CThostFtdcOrderField
# ///经纪公司代码
l_dict["BrokerID"] = pOrder.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pOrder.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pOrder.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///报单引用
l_dict["OrderRef"] = pOrder.OrderRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pOrder.UserID.decode(encoding="gb18030", errors="ignore")
# ///报单价格条件
l_dict["OrderPriceType"] = pOrder.OrderPriceType.decode(encoding="gb18030", errors="ignore")
# ///买卖方向
l_dict["Direction"] = pOrder.Direction.decode(encoding="gb18030", errors="ignore")
# ///组合开平标志
l_dict["CombOffsetFlag"] = pOrder.CombOffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///组合投机套保标志
l_dict["CombHedgeFlag"] = pOrder.CombHedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///价格
l_dict["LimitPrice"] = pOrder.LimitPrice
# ///数量
l_dict["VolumeTotalOriginal"] = pOrder.VolumeTotalOriginal
# ///有效期类型
l_dict["TimeCondition"] = pOrder.TimeCondition.decode(encoding="gb18030", errors="ignore")
# ///GTD日期
l_dict["GTDDate"] = pOrder.GTDDate.decode(encoding="gb18030", errors="ignore")
# ///成交量类型
l_dict["VolumeCondition"] = pOrder.VolumeCondition.decode(encoding="gb18030", errors="ignore")
# ///最小成交量
l_dict["MinVolume"] = pOrder.MinVolume
# ///触发条件
l_dict["ContingentCondition"] = pOrder.ContingentCondition.decode(encoding="gb18030", errors="ignore")
# ///止损价
l_dict["StopPrice"] = pOrder.StopPrice
# ///强平原因
l_dict["ForceCloseReason"] = pOrder.ForceCloseReason.decode(encoding="gb18030", errors="ignore")
# ///自动挂起标志
l_dict["IsAutoSuspend"] = pOrder.IsAutoSuspend
# ///业务单元
l_dict["BusinessUnit"] = pOrder.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pOrder.RequestID
# ///本地报单编号
l_dict["OrderLocalID"] = pOrder.OrderLocalID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pOrder.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pOrder.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pOrder.ClientID.decode(encoding="gb18030", errors="ignore")
# ///合约在交易所的代码
l_dict["ExchangeInstID"] = pOrder.ExchangeInstID.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pOrder.TraderID.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pOrder.InstallID
# ///报单提交状态
l_dict["OrderSubmitStatus"] = pOrder.OrderSubmitStatus.decode(encoding="gb18030", errors="ignore")
# ///报单提示序号
l_dict["NotifySequence"] = pOrder.NotifySequence
# ///交易日
l_dict["TradingDay"] = pOrder.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pOrder.SettlementID
# ///报单编号
l_dict["OrderSysID"] = pOrder.OrderSysID.decode(encoding="gb18030", errors="ignore")
# ///报单来源
l_dict["OrderSource"] = pOrder.OrderSource.decode(encoding="gb18030", errors="ignore")
# ///报单状态
l_dict["OrderStatus"] = pOrder.OrderStatus.decode(encoding="gb18030", errors="ignore")
# ///报单类型
l_dict["OrderType"] = pOrder.OrderType.decode(encoding="gb18030", errors="ignore")
# ///今成交数量
l_dict["VolumeTraded"] = pOrder.VolumeTraded
# ///剩余数量
l_dict["VolumeTotal"] = pOrder.VolumeTotal
# ///报单日期
l_dict["InsertDate"] = pOrder.InsertDate.decode(encoding="gb18030", errors="ignore")
# ///委托时间
l_dict["InsertTime"] = pOrder.InsertTime.decode(encoding="gb18030", errors="ignore")
# ///激活时间
l_dict["ActiveTime"] = pOrder.ActiveTime.decode(encoding="gb18030", errors="ignore")
# ///挂起时间
l_dict["SuspendTime"] = pOrder.SuspendTime.decode(encoding="gb18030", errors="ignore")
# ///最后修改时间
l_dict["UpdateTime"] = pOrder.UpdateTime.decode(encoding="gb18030", errors="ignore")
# ///撤销时间
l_dict["CancelTime"] = pOrder.CancelTime.decode(encoding="gb18030", errors="ignore")
# ///最后修改交易所交易员代码
l_dict["ActiveTraderID"] = pOrder.ActiveTraderID.decode(encoding="gb18030", errors="ignore")
# ///结算会员编号
l_dict["ClearingPartID"] = pOrder.ClearingPartID.decode(encoding="gb18030", errors="ignore")
# ///序号
l_dict["SequenceNo"] = pOrder.SequenceNo
# ///前置编号
l_dict["FrontID"] = pOrder.FrontID
# ///会话编号
l_dict["SessionID"] = pOrder.SessionID
# ///用户端产品信息
l_dict["UserProductInfo"] = pOrder.UserProductInfo.decode(encoding="gb18030", errors="ignore")
# ///状态信息
l_dict["StatusMsg"] = pOrder.StatusMsg.decode(encoding="gb18030", errors="ignore")
# ///用户强评标志
l_dict["UserForceClose"] = pOrder.UserForceClose
# ///操作用户代码
l_dict["ActiveUserID"] = pOrder.ActiveUserID.decode(encoding="gb18030", errors="ignore")
# ///经纪公司报单编号
l_dict["BrokerOrderSeq"] = pOrder.BrokerOrderSeq
# ///相关报单
l_dict["RelativeOrderSysID"] = pOrder.RelativeOrderSysID.decode(encoding="gb18030", errors="ignore")
# ///郑商所成交数量
l_dict["ZCETotalTradedVolume"] = pOrder.ZCETotalTradedVolume
# ///互换单标志
l_dict["IsSwapOrder"] = pOrder.IsSwapOrder
# ///营业部编号
l_dict["BranchID"] = pOrder.BranchID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pOrder.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///资金账号
l_dict["AccountID"] = pOrder.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pOrder.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pOrder.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pOrder.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnTrade(self, pTrade):
'''
///成交通知
'''
self.PTP_Algos.DumpRspDict("T_Trade",pTrade)
l_dict={}
"""CThostFtdcTradeField
# ///经纪公司代码
l_dict["BrokerID"] = pTrade.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pTrade.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pTrade.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///报单引用
l_dict["OrderRef"] = pTrade.OrderRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pTrade.UserID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pTrade.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///成交编号
l_dict["TradeID"] = pTrade.TradeID.decode(encoding="gb18030", errors="ignore")
# ///买卖方向
l_dict["Direction"] = pTrade.Direction.decode(encoding="gb18030", errors="ignore")
# ///报单编号
l_dict["OrderSysID"] = pTrade.OrderSysID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pTrade.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pTrade.ClientID.decode(encoding="gb18030", errors="ignore")
# ///交易角色
l_dict["TradingRole"] = pTrade.TradingRole.decode(encoding="gb18030", errors="ignore")
# ///合约在交易所的代码
l_dict["ExchangeInstID"] = pTrade.ExchangeInstID.decode(encoding="gb18030", errors="ignore")
# ///开平标志
l_dict["OffsetFlag"] = pTrade.OffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pTrade.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///价格
l_dict["Price"] = pTrade.Price
# ///数量
l_dict["Volume"] = pTrade.Volume
# ///成交时期
l_dict["TradeDate"] = pTrade.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///成交时间
l_dict["TradeTime"] = pTrade.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///成交类型
l_dict["TradeType"] = pTrade.TradeType.decode(encoding="gb18030", errors="ignore")
# ///成交价来源
l_dict["PriceSource"] = pTrade.PriceSource.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pTrade.TraderID.decode(encoding="gb18030", errors="ignore")
# ///本地报单编号
l_dict["OrderLocalID"] = pTrade.OrderLocalID.decode(encoding="gb18030", errors="ignore")
# ///结算会员编号
l_dict["ClearingPartID"] = pTrade.ClearingPartID.decode(encoding="gb18030", errors="ignore")
# ///业务单元
l_dict["BusinessUnit"] = pTrade.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///序号
l_dict["SequenceNo"] = pTrade.SequenceNo
# ///交易日
l_dict["TradingDay"] = pTrade.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pTrade.SettlementID
# ///经纪公司报单编号
l_dict["BrokerOrderSeq"] = pTrade.BrokerOrderSeq
# ///成交来源
l_dict["TradeSource"] = pTrade.TradeSource.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pTrade.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnErrRtnOrderInsert(self, pInputOrder, pRspInfo):
'''
///报单录入错误回报
'''
self.PTP_Algos.DumpRspDict("T_InputOrder",pInputOrder)
l_dict={}
"""CThostFtdcInputOrderField
# ///经纪公司代码
l_dict["BrokerID"] = pInputOrder.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInputOrder.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pInputOrder.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///报单引用
l_dict["OrderRef"] = pInputOrder.OrderRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pInputOrder.UserID.decode(encoding="gb18030", errors="ignore")
# ///报单价格条件
l_dict["OrderPriceType"] = pInputOrder.OrderPriceType.decode(encoding="gb18030", errors="ignore")
# ///买卖方向
l_dict["Direction"] = pInputOrder.Direction.decode(encoding="gb18030", errors="ignore")
# ///组合开平标志
l_dict["CombOffsetFlag"] = pInputOrder.CombOffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///组合投机套保标志
l_dict["CombHedgeFlag"] = pInputOrder.CombHedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///价格
l_dict["LimitPrice"] = pInputOrder.LimitPrice
# ///数量
l_dict["VolumeTotalOriginal"] = pInputOrder.VolumeTotalOriginal
# ///有效期类型
l_dict["TimeCondition"] = pInputOrder.TimeCondition.decode(encoding="gb18030", errors="ignore")
# ///GTD日期
l_dict["GTDDate"] = pInputOrder.GTDDate.decode(encoding="gb18030", errors="ignore")
# ///成交量类型
l_dict["VolumeCondition"] = pInputOrder.VolumeCondition.decode(encoding="gb18030", errors="ignore")
# ///最小成交量
l_dict["MinVolume"] = pInputOrder.MinVolume
# ///触发条件
l_dict["ContingentCondition"] = pInputOrder.ContingentCondition.decode(encoding="gb18030", errors="ignore")
# ///止损价
l_dict["StopPrice"] = pInputOrder.StopPrice
# ///强平原因
l_dict["ForceCloseReason"] = pInputOrder.ForceCloseReason.decode(encoding="gb18030", errors="ignore")
# ///自动挂起标志
l_dict["IsAutoSuspend"] = pInputOrder.IsAutoSuspend
# ///业务单元
l_dict["BusinessUnit"] = pInputOrder.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pInputOrder.RequestID
# ///用户强评标志
l_dict["UserForceClose"] = pInputOrder.UserForceClose
# ///互换单标志
l_dict["IsSwapOrder"] = pInputOrder.IsSwapOrder
# ///交易所代码
l_dict["ExchangeID"] = pInputOrder.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInputOrder.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///资金账号
l_dict["AccountID"] = pInputOrder.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pInputOrder.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///交易编码
l_dict["ClientID"] = pInputOrder.ClientID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pInputOrder.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pInputOrder.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnErrRtnOrderAction(self, pOrderAction, pRspInfo):
'''
///报单操作错误回报
'''
self.PTP_Algos.DumpRspDict("T_OrderAction",pOrderAction)
l_dict={}
"""CThostFtdcOrderActionField
# ///经纪公司代码
l_dict["BrokerID"] = pOrderAction.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pOrderAction.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///报单操作引用
l_dict["OrderActionRef"] = pOrderAction.OrderActionRef
# ///报单引用
l_dict["OrderRef"] = pOrderAction.OrderRef.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pOrderAction.RequestID
# ///前置编号
l_dict["FrontID"] = pOrderAction.FrontID
# ///会话编号
l_dict["SessionID"] = pOrderAction.SessionID
# ///交易所代码
l_dict["ExchangeID"] = pOrderAction.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///报单编号
l_dict["OrderSysID"] = pOrderAction.OrderSysID.decode(encoding="gb18030", errors="ignore")
# ///操作标志
l_dict["ActionFlag"] = pOrderAction.ActionFlag.decode(encoding="gb18030", errors="ignore")
# ///价格
l_dict["LimitPrice"] = pOrderAction.LimitPrice
# ///数量变化
l_dict["VolumeChange"] = pOrderAction.VolumeChange
# ///操作日期
l_dict["ActionDate"] = pOrderAction.ActionDate.decode(encoding="gb18030", errors="ignore")
# ///操作时间
l_dict["ActionTime"] = pOrderAction.ActionTime.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pOrderAction.TraderID.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pOrderAction.InstallID
# ///本地报单编号
l_dict["OrderLocalID"] = pOrderAction.OrderLocalID.decode(encoding="gb18030", errors="ignore")
# ///操作本地编号
l_dict["ActionLocalID"] = pOrderAction.ActionLocalID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pOrderAction.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pOrderAction.ClientID.decode(encoding="gb18030", errors="ignore")
# ///业务单元
l_dict["BusinessUnit"] = pOrderAction.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///报单操作状态
l_dict["OrderActionStatus"] = pOrderAction.OrderActionStatus.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pOrderAction.UserID.decode(encoding="gb18030", errors="ignore")
# ///状态信息
l_dict["StatusMsg"] = pOrderAction.StatusMsg.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pOrderAction.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///营业部编号
l_dict["BranchID"] = pOrderAction.BranchID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pOrderAction.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pOrderAction.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pOrderAction.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnInstrumentStatus(self, pInstrumentStatus):
'''
///合约交易状态通知
'''
self.PTP_Algos.push_OnRtnInstrumentStatus("T_InstrumentStatus",pInstrumentStatus)
l_dict={}
"""CThostFtdcInstrumentStatusField
# ///交易所代码
l_dict["ExchangeID"] = pInstrumentStatus.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///合约在交易所的代码
l_dict["ExchangeInstID"] = pInstrumentStatus.ExchangeInstID.decode(encoding="gb18030", errors="ignore")
# ///结算组代码
l_dict["SettlementGroupID"] = pInstrumentStatus.SettlementGroupID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pInstrumentStatus.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///合约交易状态
l_dict["InstrumentStatus"] = pInstrumentStatus.InstrumentStatus.decode(encoding="gb18030", errors="ignore")
# ///交易阶段编号
l_dict["TradingSegmentSN"] = pInstrumentStatus.TradingSegmentSN
# ///进入本状态时间
l_dict["EnterTime"] = pInstrumentStatus.EnterTime.decode(encoding="gb18030", errors="ignore")
# ///进入本状态原因
l_dict["EnterReason"] = pInstrumentStatus.EnterReason.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnBulletin(self, pBulletin):
'''
///交易所公告通知
'''
self.PTP_Algos.DumpRspDict("T_Bulletin",pBulletin)
l_dict={}
"""CThostFtdcBulletinField
# ///交易所代码
l_dict["ExchangeID"] = pBulletin.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///交易日
l_dict["TradingDay"] = pBulletin.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///公告编号
l_dict["BulletinID"] = pBulletin.BulletinID
# ///序列号
l_dict["SequenceNo"] = pBulletin.SequenceNo
# ///公告类型
l_dict["NewsType"] = pBulletin.NewsType.decode(encoding="gb18030", errors="ignore")
# ///紧急程度
l_dict["NewsUrgency"] = pBulletin.NewsUrgency.decode(encoding="gb18030", errors="ignore")
# ///发送时间
l_dict["SendTime"] = pBulletin.SendTime.decode(encoding="gb18030", errors="ignore")
# ///消息摘要
l_dict["Abstract"] = pBulletin.Abstract.decode(encoding="gb18030", errors="ignore")
# ///消息来源
l_dict["ComeFrom"] = pBulletin.ComeFrom.decode(encoding="gb18030", errors="ignore")
# ///消息正文
l_dict["Content"] = pBulletin.Content.decode(encoding="gb18030", errors="ignore")
# ///WEB地址
l_dict["URLLink"] = pBulletin.URLLink.decode(encoding="gb18030", errors="ignore")
# ///市场代码
l_dict["MarketID"] = pBulletin.MarketID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnTradingNotice(self, pTradingNoticeInfo):
'''
///交易通知
'''
self.PTP_Algos.DumpRspDict("T_TradingNoticeInfo",pTradingNoticeInfo)
l_dict={}
"""CThostFtdcTradingNoticeInfoField
# ///经纪公司代码
l_dict["BrokerID"] = pTradingNoticeInfo.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pTradingNoticeInfo.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///发送时间
l_dict["SendTime"] = pTradingNoticeInfo.SendTime.decode(encoding="gb18030", errors="ignore")
# ///消息正文
l_dict["FieldContent"] = pTradingNoticeInfo.FieldContent.decode(encoding="gb18030", errors="ignore")
# ///序列系列号
l_dict["SequenceSeries"] = pTradingNoticeInfo.SequenceSeries
# ///序列号
l_dict["SequenceNo"] = pTradingNoticeInfo.SequenceNo
# ///投资单元代码
l_dict["InvestUnitID"] = pTradingNoticeInfo.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnErrorConditionalOrder(self, pErrorConditionalOrder):
'''
///提示条件单校验错误
'''
self.PTP_Algos.DumpRspDict("T_ErrorConditionalOrder",pErrorConditionalOrder)
l_dict={}
"""CThostFtdcErrorConditionalOrderField
# ///经纪公司代码
l_dict["BrokerID"] = pErrorConditionalOrder.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pErrorConditionalOrder.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pErrorConditionalOrder.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///报单引用
l_dict["OrderRef"] = pErrorConditionalOrder.OrderRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pErrorConditionalOrder.UserID.decode(encoding="gb18030", errors="ignore")
# ///报单价格条件
l_dict["OrderPriceType"] = pErrorConditionalOrder.OrderPriceType.decode(encoding="gb18030", errors="ignore")
# ///买卖方向
l_dict["Direction"] = pErrorConditionalOrder.Direction.decode(encoding="gb18030", errors="ignore")
# ///组合开平标志
l_dict["CombOffsetFlag"] = pErrorConditionalOrder.CombOffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///组合投机套保标志
l_dict["CombHedgeFlag"] = pErrorConditionalOrder.CombHedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///价格
l_dict["LimitPrice"] = pErrorConditionalOrder.LimitPrice
# ///数量
l_dict["VolumeTotalOriginal"] = pErrorConditionalOrder.VolumeTotalOriginal
# ///有效期类型
l_dict["TimeCondition"] = pErrorConditionalOrder.TimeCondition.decode(encoding="gb18030", errors="ignore")
# ///GTD日期
l_dict["GTDDate"] = pErrorConditionalOrder.GTDDate.decode(encoding="gb18030", errors="ignore")
# ///成交量类型
l_dict["VolumeCondition"] = pErrorConditionalOrder.VolumeCondition.decode(encoding="gb18030", errors="ignore")
# ///最小成交量
l_dict["MinVolume"] = pErrorConditionalOrder.MinVolume
# ///触发条件
l_dict["ContingentCondition"] = pErrorConditionalOrder.ContingentCondition.decode(encoding="gb18030", errors="ignore")
# ///止损价
l_dict["StopPrice"] = pErrorConditionalOrder.StopPrice
# ///强平原因
l_dict["ForceCloseReason"] = pErrorConditionalOrder.ForceCloseReason.decode(encoding="gb18030", errors="ignore")
# ///自动挂起标志
l_dict["IsAutoSuspend"] = pErrorConditionalOrder.IsAutoSuspend
# ///业务单元
l_dict["BusinessUnit"] = pErrorConditionalOrder.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pErrorConditionalOrder.RequestID
# ///本地报单编号
l_dict["OrderLocalID"] = pErrorConditionalOrder.OrderLocalID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pErrorConditionalOrder.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pErrorConditionalOrder.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pErrorConditionalOrder.ClientID.decode(encoding="gb18030", errors="ignore")
# ///合约在交易所的代码
l_dict["ExchangeInstID"] = pErrorConditionalOrder.ExchangeInstID.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pErrorConditionalOrder.TraderID.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pErrorConditionalOrder.InstallID
# ///报单提交状态
l_dict["OrderSubmitStatus"] = pErrorConditionalOrder.OrderSubmitStatus.decode(encoding="gb18030", errors="ignore")
# ///报单提示序号
l_dict["NotifySequence"] = pErrorConditionalOrder.NotifySequence
# ///交易日
l_dict["TradingDay"] = pErrorConditionalOrder.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pErrorConditionalOrder.SettlementID
# ///报单编号
l_dict["OrderSysID"] = pErrorConditionalOrder.OrderSysID.decode(encoding="gb18030", errors="ignore")
# ///报单来源
l_dict["OrderSource"] = pErrorConditionalOrder.OrderSource.decode(encoding="gb18030", errors="ignore")
# ///报单状态
l_dict["OrderStatus"] = pErrorConditionalOrder.OrderStatus.decode(encoding="gb18030", errors="ignore")
# ///报单类型
l_dict["OrderType"] = pErrorConditionalOrder.OrderType.decode(encoding="gb18030", errors="ignore")
# ///今成交数量
l_dict["VolumeTraded"] = pErrorConditionalOrder.VolumeTraded
# ///剩余数量
l_dict["VolumeTotal"] = pErrorConditionalOrder.VolumeTotal
# ///报单日期
l_dict["InsertDate"] = pErrorConditionalOrder.InsertDate.decode(encoding="gb18030", errors="ignore")
# ///委托时间
l_dict["InsertTime"] = pErrorConditionalOrder.InsertTime.decode(encoding="gb18030", errors="ignore")
# ///激活时间
l_dict["ActiveTime"] = pErrorConditionalOrder.ActiveTime.decode(encoding="gb18030", errors="ignore")
# ///挂起时间
l_dict["SuspendTime"] = pErrorConditionalOrder.SuspendTime.decode(encoding="gb18030", errors="ignore")
# ///最后修改时间
l_dict["UpdateTime"] = pErrorConditionalOrder.UpdateTime.decode(encoding="gb18030", errors="ignore")
# ///撤销时间
l_dict["CancelTime"] = pErrorConditionalOrder.CancelTime.decode(encoding="gb18030", errors="ignore")
# ///最后修改交易所交易员代码
l_dict["ActiveTraderID"] = pErrorConditionalOrder.ActiveTraderID.decode(encoding="gb18030", errors="ignore")
# ///结算会员编号
l_dict["ClearingPartID"] = pErrorConditionalOrder.ClearingPartID.decode(encoding="gb18030", errors="ignore")
# ///序号
l_dict["SequenceNo"] = pErrorConditionalOrder.SequenceNo
# ///前置编号
l_dict["FrontID"] = pErrorConditionalOrder.FrontID
# ///会话编号
l_dict["SessionID"] = pErrorConditionalOrder.SessionID
# ///用户端产品信息
l_dict["UserProductInfo"] = pErrorConditionalOrder.UserProductInfo.decode(encoding="gb18030", errors="ignore")
# ///状态信息
l_dict["StatusMsg"] = pErrorConditionalOrder.StatusMsg.decode(encoding="gb18030", errors="ignore")
# ///用户强评标志
l_dict["UserForceClose"] = pErrorConditionalOrder.UserForceClose
# ///操作用户代码
l_dict["ActiveUserID"] = pErrorConditionalOrder.ActiveUserID.decode(encoding="gb18030", errors="ignore")
# ///经纪公司报单编号
l_dict["BrokerOrderSeq"] = pErrorConditionalOrder.BrokerOrderSeq
# ///相关报单
l_dict["RelativeOrderSysID"] = pErrorConditionalOrder.RelativeOrderSysID.decode(encoding="gb18030", errors="ignore")
# ///郑商所成交数量
l_dict["ZCETotalTradedVolume"] = pErrorConditionalOrder.ZCETotalTradedVolume
# ///错误代码
l_dict["ErrorID"] = pErrorConditionalOrder.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pErrorConditionalOrder.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///互换单标志
l_dict["IsSwapOrder"] = pErrorConditionalOrder.IsSwapOrder
# ///营业部编号
l_dict["BranchID"] = pErrorConditionalOrder.BranchID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pErrorConditionalOrder.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///资金账号
l_dict["AccountID"] = pErrorConditionalOrder.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pErrorConditionalOrder.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pErrorConditionalOrder.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pErrorConditionalOrder.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnExecOrder(self, pExecOrder):
'''
///执行宣告通知
'''
self.PTP_Algos.DumpRspDict("T_ExecOrder",pExecOrder)
l_dict={}
"""CThostFtdcExecOrderField
# ///经纪公司代码
l_dict["BrokerID"] = pExecOrder.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pExecOrder.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pExecOrder.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///执行宣告引用
l_dict["ExecOrderRef"] = pExecOrder.ExecOrderRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pExecOrder.UserID.decode(encoding="gb18030", errors="ignore")
# ///数量
l_dict["Volume"] = pExecOrder.Volume
# ///请求编号
l_dict["RequestID"] = pExecOrder.RequestID
# ///业务单元
l_dict["BusinessUnit"] = pExecOrder.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///开平标志
l_dict["OffsetFlag"] = pExecOrder.OffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pExecOrder.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///执行类型
l_dict["ActionType"] = pExecOrder.ActionType.decode(encoding="gb18030", errors="ignore")
# ///保留头寸申请的持仓方向
l_dict["PosiDirection"] = pExecOrder.PosiDirection.decode(encoding="gb18030", errors="ignore")
# ///期权行权后是否保留期货头寸的标记,该字段已废弃
l_dict["ReservePositionFlag"] = pExecOrder.ReservePositionFlag.decode(encoding="gb18030", errors="ignore")
# ///期权行权后生成的头寸是否自动平仓
l_dict["CloseFlag"] = pExecOrder.CloseFlag.decode(encoding="gb18030", errors="ignore")
# ///本地执行宣告编号
l_dict["ExecOrderLocalID"] = pExecOrder.ExecOrderLocalID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pExecOrder.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pExecOrder.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pExecOrder.ClientID.decode(encoding="gb18030", errors="ignore")
# ///合约在交易所的代码
l_dict["ExchangeInstID"] = pExecOrder.ExchangeInstID.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pExecOrder.TraderID.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pExecOrder.InstallID
# ///执行宣告提交状态
l_dict["OrderSubmitStatus"] = pExecOrder.OrderSubmitStatus.decode(encoding="gb18030", errors="ignore")
# ///报单提示序号
l_dict["NotifySequence"] = pExecOrder.NotifySequence
# ///交易日
l_dict["TradingDay"] = pExecOrder.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pExecOrder.SettlementID
# ///执行宣告编号
l_dict["ExecOrderSysID"] = pExecOrder.ExecOrderSysID.decode(encoding="gb18030", errors="ignore")
# ///报单日期
l_dict["InsertDate"] = pExecOrder.InsertDate.decode(encoding="gb18030", errors="ignore")
# ///插入时间
l_dict["InsertTime"] = pExecOrder.InsertTime.decode(encoding="gb18030", errors="ignore")
# ///撤销时间
l_dict["CancelTime"] = pExecOrder.CancelTime.decode(encoding="gb18030", errors="ignore")
# ///执行结果
l_dict["ExecResult"] = pExecOrder.ExecResult.decode(encoding="gb18030", errors="ignore")
# ///结算会员编号
l_dict["ClearingPartID"] = pExecOrder.ClearingPartID.decode(encoding="gb18030", errors="ignore")
# ///序号
l_dict["SequenceNo"] = pExecOrder.SequenceNo
# ///前置编号
l_dict["FrontID"] = pExecOrder.FrontID
# ///会话编号
l_dict["SessionID"] = pExecOrder.SessionID
# ///用户端产品信息
l_dict["UserProductInfo"] = pExecOrder.UserProductInfo.decode(encoding="gb18030", errors="ignore")
# ///状态信息
l_dict["StatusMsg"] = pExecOrder.StatusMsg.decode(encoding="gb18030", errors="ignore")
# ///操作用户代码
l_dict["ActiveUserID"] = pExecOrder.ActiveUserID.decode(encoding="gb18030", errors="ignore")
# ///经纪公司报单编号
l_dict["BrokerExecOrderSeq"] = pExecOrder.BrokerExecOrderSeq
# ///营业部编号
l_dict["BranchID"] = pExecOrder.BranchID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pExecOrder.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///资金账号
l_dict["AccountID"] = pExecOrder.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pExecOrder.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pExecOrder.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pExecOrder.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnErrRtnExecOrderInsert(self, pInputExecOrder, pRspInfo):
'''
///执行宣告录入错误回报
'''
self.PTP_Algos.DumpRspDict("T_InputExecOrder",pInputExecOrder)
l_dict={}
"""CThostFtdcInputExecOrderField
# ///经纪公司代码
l_dict["BrokerID"] = pInputExecOrder.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInputExecOrder.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pInputExecOrder.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///执行宣告引用
l_dict["ExecOrderRef"] = pInputExecOrder.ExecOrderRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pInputExecOrder.UserID.decode(encoding="gb18030", errors="ignore")
# ///数量
l_dict["Volume"] = pInputExecOrder.Volume
# ///请求编号
l_dict["RequestID"] = pInputExecOrder.RequestID
# ///业务单元
l_dict["BusinessUnit"] = pInputExecOrder.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///开平标志
l_dict["OffsetFlag"] = pInputExecOrder.OffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pInputExecOrder.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///执行类型
l_dict["ActionType"] = pInputExecOrder.ActionType.decode(encoding="gb18030", errors="ignore")
# ///保留头寸申请的持仓方向
l_dict["PosiDirection"] = pInputExecOrder.PosiDirection.decode(encoding="gb18030", errors="ignore")
# ///期权行权后是否保留期货头寸的标记,该字段已废弃
l_dict["ReservePositionFlag"] = pInputExecOrder.ReservePositionFlag.decode(encoding="gb18030", errors="ignore")
# ///期权行权后生成的头寸是否自动平仓
l_dict["CloseFlag"] = pInputExecOrder.CloseFlag.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pInputExecOrder.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInputExecOrder.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///资金账号
l_dict["AccountID"] = pInputExecOrder.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pInputExecOrder.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///交易编码
l_dict["ClientID"] = pInputExecOrder.ClientID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pInputExecOrder.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pInputExecOrder.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnErrRtnExecOrderAction(self, pExecOrderAction, pRspInfo):
'''
///执行宣告操作错误回报
'''
self.PTP_Algos.DumpRspDict("T_ExecOrderAction",pExecOrderAction)
l_dict={}
"""CThostFtdcExecOrderActionField
# ///经纪公司代码
l_dict["BrokerID"] = pExecOrderAction.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pExecOrderAction.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///执行宣告操作引用
l_dict["ExecOrderActionRef"] = pExecOrderAction.ExecOrderActionRef
# ///执行宣告引用
l_dict["ExecOrderRef"] = pExecOrderAction.ExecOrderRef.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pExecOrderAction.RequestID
# ///前置编号
l_dict["FrontID"] = pExecOrderAction.FrontID
# ///会话编号
l_dict["SessionID"] = pExecOrderAction.SessionID
# ///交易所代码
l_dict["ExchangeID"] = pExecOrderAction.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///执行宣告操作编号
l_dict["ExecOrderSysID"] = pExecOrderAction.ExecOrderSysID.decode(encoding="gb18030", errors="ignore")
# ///操作标志
l_dict["ActionFlag"] = pExecOrderAction.ActionFlag.decode(encoding="gb18030", errors="ignore")
# ///操作日期
l_dict["ActionDate"] = pExecOrderAction.ActionDate.decode(encoding="gb18030", errors="ignore")
# ///操作时间
l_dict["ActionTime"] = pExecOrderAction.ActionTime.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pExecOrderAction.TraderID.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pExecOrderAction.InstallID
# ///本地执行宣告编号
l_dict["ExecOrderLocalID"] = pExecOrderAction.ExecOrderLocalID.decode(encoding="gb18030", errors="ignore")
# ///操作本地编号
l_dict["ActionLocalID"] = pExecOrderAction.ActionLocalID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pExecOrderAction.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pExecOrderAction.ClientID.decode(encoding="gb18030", errors="ignore")
# ///业务单元
l_dict["BusinessUnit"] = pExecOrderAction.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///报单操作状态
l_dict["OrderActionStatus"] = pExecOrderAction.OrderActionStatus.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pExecOrderAction.UserID.decode(encoding="gb18030", errors="ignore")
# ///执行类型
l_dict["ActionType"] = pExecOrderAction.ActionType.decode(encoding="gb18030", errors="ignore")
# ///状态信息
l_dict["StatusMsg"] = pExecOrderAction.StatusMsg.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pExecOrderAction.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///营业部编号
l_dict["BranchID"] = pExecOrderAction.BranchID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pExecOrderAction.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pExecOrderAction.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pExecOrderAction.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnErrRtnForQuoteInsert(self, pInputForQuote, pRspInfo):
'''
///询价录入错误回报
'''
self.PTP_Algos.DumpRspDict("T_InputForQuote",pInputForQuote)
l_dict={}
"""CThostFtdcInputForQuoteField
# ///经纪公司代码
l_dict["BrokerID"] = pInputForQuote.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInputForQuote.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pInputForQuote.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///询价引用
l_dict["ForQuoteRef"] = pInputForQuote.ForQuoteRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pInputForQuote.UserID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pInputForQuote.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInputForQuote.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pInputForQuote.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pInputForQuote.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnQuote(self, pQuote):
'''
///报价通知
'''
self.PTP_Algos.DumpRspDict("T_Quote",pQuote)
l_dict={}
"""CThostFtdcQuoteField
# ///经纪公司代码
l_dict["BrokerID"] = pQuote.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pQuote.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pQuote.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///报价引用
l_dict["QuoteRef"] = pQuote.QuoteRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pQuote.UserID.decode(encoding="gb18030", errors="ignore")
# ///卖价格
l_dict["AskPrice"] = pQuote.AskPrice
# ///买价格
l_dict["BidPrice"] = pQuote.BidPrice
# ///卖数量
l_dict["AskVolume"] = pQuote.AskVolume
# ///买数量
l_dict["BidVolume"] = pQuote.BidVolume
# ///请求编号
l_dict["RequestID"] = pQuote.RequestID
# ///业务单元
l_dict["BusinessUnit"] = pQuote.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///卖开平标志
l_dict["AskOffsetFlag"] = pQuote.AskOffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///买开平标志
l_dict["BidOffsetFlag"] = pQuote.BidOffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///卖投机套保标志
l_dict["AskHedgeFlag"] = pQuote.AskHedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///买投机套保标志
l_dict["BidHedgeFlag"] = pQuote.BidHedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///本地报价编号
l_dict["QuoteLocalID"] = pQuote.QuoteLocalID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pQuote.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pQuote.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pQuote.ClientID.decode(encoding="gb18030", errors="ignore")
# ///合约在交易所的代码
l_dict["ExchangeInstID"] = pQuote.ExchangeInstID.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pQuote.TraderID.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pQuote.InstallID
# ///报价提示序号
l_dict["NotifySequence"] = pQuote.NotifySequence
# ///报价提交状态
l_dict["OrderSubmitStatus"] = pQuote.OrderSubmitStatus.decode(encoding="gb18030", errors="ignore")
# ///交易日
l_dict["TradingDay"] = pQuote.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pQuote.SettlementID
# ///报价编号
l_dict["QuoteSysID"] = pQuote.QuoteSysID.decode(encoding="gb18030", errors="ignore")
# ///报单日期
l_dict["InsertDate"] = pQuote.InsertDate.decode(encoding="gb18030", errors="ignore")
# ///插入时间
l_dict["InsertTime"] = pQuote.InsertTime.decode(encoding="gb18030", errors="ignore")
# ///撤销时间
l_dict["CancelTime"] = pQuote.CancelTime.decode(encoding="gb18030", errors="ignore")
# ///报价状态
l_dict["QuoteStatus"] = pQuote.QuoteStatus.decode(encoding="gb18030", errors="ignore")
# ///结算会员编号
l_dict["ClearingPartID"] = pQuote.ClearingPartID.decode(encoding="gb18030", errors="ignore")
# ///序号
l_dict["SequenceNo"] = pQuote.SequenceNo
# ///卖方报单编号
l_dict["AskOrderSysID"] = pQuote.AskOrderSysID.decode(encoding="gb18030", errors="ignore")
# ///买方报单编号
l_dict["BidOrderSysID"] = pQuote.BidOrderSysID.decode(encoding="gb18030", errors="ignore")
# ///前置编号
l_dict["FrontID"] = pQuote.FrontID
# ///会话编号
l_dict["SessionID"] = pQuote.SessionID
# ///用户端产品信息
l_dict["UserProductInfo"] = pQuote.UserProductInfo.decode(encoding="gb18030", errors="ignore")
# ///状态信息
l_dict["StatusMsg"] = pQuote.StatusMsg.decode(encoding="gb18030", errors="ignore")
# ///操作用户代码
l_dict["ActiveUserID"] = pQuote.ActiveUserID.decode(encoding="gb18030", errors="ignore")
# ///经纪公司报价编号
l_dict["BrokerQuoteSeq"] = pQuote.BrokerQuoteSeq
# ///衍生卖报单引用
l_dict["AskOrderRef"] = pQuote.AskOrderRef.decode(encoding="gb18030", errors="ignore")
# ///衍生买报单引用
l_dict["BidOrderRef"] = pQuote.BidOrderRef.decode(encoding="gb18030", errors="ignore")
# ///应价编号
l_dict["ForQuoteSysID"] = pQuote.ForQuoteSysID.decode(encoding="gb18030", errors="ignore")
# ///营业部编号
l_dict["BranchID"] = pQuote.BranchID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pQuote.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///资金账号
l_dict["AccountID"] = pQuote.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pQuote.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pQuote.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pQuote.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnErrRtnQuoteInsert(self, pInputQuote, pRspInfo):
'''
///报价录入错误回报
'''
self.PTP_Algos.DumpRspDict("T_InputQuote",pInputQuote)
l_dict={}
"""CThostFtdcInputQuoteField
# ///经纪公司代码
l_dict["BrokerID"] = pInputQuote.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInputQuote.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pInputQuote.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///报价引用
l_dict["QuoteRef"] = pInputQuote.QuoteRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pInputQuote.UserID.decode(encoding="gb18030", errors="ignore")
# ///卖价格
l_dict["AskPrice"] = pInputQuote.AskPrice
# ///买价格
l_dict["BidPrice"] = pInputQuote.BidPrice
# ///卖数量
l_dict["AskVolume"] = pInputQuote.AskVolume
# ///买数量
l_dict["BidVolume"] = pInputQuote.BidVolume
# ///请求编号
l_dict["RequestID"] = pInputQuote.RequestID
# ///业务单元
l_dict["BusinessUnit"] = pInputQuote.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///卖开平标志
l_dict["AskOffsetFlag"] = pInputQuote.AskOffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///买开平标志
l_dict["BidOffsetFlag"] = pInputQuote.BidOffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///卖投机套保标志
l_dict["AskHedgeFlag"] = pInputQuote.AskHedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///买投机套保标志
l_dict["BidHedgeFlag"] = pInputQuote.BidHedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///衍生卖报单引用
l_dict["AskOrderRef"] = pInputQuote.AskOrderRef.decode(encoding="gb18030", errors="ignore")
# ///衍生买报单引用
l_dict["BidOrderRef"] = pInputQuote.BidOrderRef.decode(encoding="gb18030", errors="ignore")
# ///应价编号
l_dict["ForQuoteSysID"] = pInputQuote.ForQuoteSysID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pInputQuote.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInputQuote.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///交易编码
l_dict["ClientID"] = pInputQuote.ClientID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pInputQuote.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pInputQuote.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnErrRtnQuoteAction(self, pQuoteAction, pRspInfo):
'''
///报价操作错误回报
'''
self.PTP_Algos.DumpRspDict("T_QuoteAction",pQuoteAction)
l_dict={}
"""CThostFtdcQuoteActionField
# ///经纪公司代码
l_dict["BrokerID"] = pQuoteAction.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pQuoteAction.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///报价操作引用
l_dict["QuoteActionRef"] = pQuoteAction.QuoteActionRef
# ///报价引用
l_dict["QuoteRef"] = pQuoteAction.QuoteRef.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pQuoteAction.RequestID
# ///前置编号
l_dict["FrontID"] = pQuoteAction.FrontID
# ///会话编号
l_dict["SessionID"] = pQuoteAction.SessionID
# ///交易所代码
l_dict["ExchangeID"] = pQuoteAction.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///报价操作编号
l_dict["QuoteSysID"] = pQuoteAction.QuoteSysID.decode(encoding="gb18030", errors="ignore")
# ///操作标志
l_dict["ActionFlag"] = pQuoteAction.ActionFlag.decode(encoding="gb18030", errors="ignore")
# ///操作日期
l_dict["ActionDate"] = pQuoteAction.ActionDate.decode(encoding="gb18030", errors="ignore")
# ///操作时间
l_dict["ActionTime"] = pQuoteAction.ActionTime.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pQuoteAction.TraderID.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pQuoteAction.InstallID
# ///本地报价编号
l_dict["QuoteLocalID"] = pQuoteAction.QuoteLocalID.decode(encoding="gb18030", errors="ignore")
# ///操作本地编号
l_dict["ActionLocalID"] = pQuoteAction.ActionLocalID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pQuoteAction.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pQuoteAction.ClientID.decode(encoding="gb18030", errors="ignore")
# ///业务单元
l_dict["BusinessUnit"] = pQuoteAction.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///报单操作状态
l_dict["OrderActionStatus"] = pQuoteAction.OrderActionStatus.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pQuoteAction.UserID.decode(encoding="gb18030", errors="ignore")
# ///状态信息
l_dict["StatusMsg"] = pQuoteAction.StatusMsg.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pQuoteAction.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///营业部编号
l_dict["BranchID"] = pQuoteAction.BranchID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pQuoteAction.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pQuoteAction.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pQuoteAction.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnForQuoteRsp(self, pForQuoteRsp):
'''
///询价通知
'''
self.PTP_Algos.DumpRspDict("T_ForQuoteRsp",pForQuoteRsp)
l_dict={}
"""CThostFtdcForQuoteRspField
# ///交易日
l_dict["TradingDay"] = pForQuoteRsp.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pForQuoteRsp.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///询价编号
l_dict["ForQuoteSysID"] = pForQuoteRsp.ForQuoteSysID.decode(encoding="gb18030", errors="ignore")
# ///询价时间
l_dict["ForQuoteTime"] = pForQuoteRsp.ForQuoteTime.decode(encoding="gb18030", errors="ignore")
# ///业务日期
l_dict["ActionDay"] = pForQuoteRsp.ActionDay.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pForQuoteRsp.ExchangeID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnCFMMCTradingAccountToken(self, pCFMMCTradingAccountToken):
'''
///保证金监控中心用户令牌
'''
self.PTP_Algos.DumpRspDict("T_CFMMCTradingAccountToken",pCFMMCTradingAccountToken)
l_dict={}
"""CThostFtdcCFMMCTradingAccountTokenField
# ///经纪公司代码
l_dict["BrokerID"] = pCFMMCTradingAccountToken.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///经纪公司统一编码
l_dict["ParticipantID"] = pCFMMCTradingAccountToken.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pCFMMCTradingAccountToken.AccountID.decode(encoding="gb18030", errors="ignore")
# ///密钥编号
l_dict["KeyID"] = pCFMMCTradingAccountToken.KeyID
# ///动态令牌
l_dict["Token"] = pCFMMCTradingAccountToken.Token.decode(encoding="gb18030", errors="ignore")
#"""
def OnErrRtnBatchOrderAction(self, pBatchOrderAction, pRspInfo):
'''
///批量报单操作错误回报
'''
self.PTP_Algos.DumpRspDict("T_BatchOrderAction",pBatchOrderAction)
l_dict={}
"""CThostFtdcBatchOrderActionField
# ///经纪公司代码
l_dict["BrokerID"] = pBatchOrderAction.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pBatchOrderAction.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///报单操作引用
l_dict["OrderActionRef"] = pBatchOrderAction.OrderActionRef
# ///请求编号
l_dict["RequestID"] = pBatchOrderAction.RequestID
# ///前置编号
l_dict["FrontID"] = pBatchOrderAction.FrontID
# ///会话编号
l_dict["SessionID"] = pBatchOrderAction.SessionID
# ///交易所代码
l_dict["ExchangeID"] = pBatchOrderAction.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///操作日期
l_dict["ActionDate"] = pBatchOrderAction.ActionDate.decode(encoding="gb18030", errors="ignore")
# ///操作时间
l_dict["ActionTime"] = pBatchOrderAction.ActionTime.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pBatchOrderAction.TraderID.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pBatchOrderAction.InstallID
# ///操作本地编号
l_dict["ActionLocalID"] = pBatchOrderAction.ActionLocalID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pBatchOrderAction.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pBatchOrderAction.ClientID.decode(encoding="gb18030", errors="ignore")
# ///业务单元
l_dict["BusinessUnit"] = pBatchOrderAction.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///报单操作状态
l_dict["OrderActionStatus"] = pBatchOrderAction.OrderActionStatus.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pBatchOrderAction.UserID.decode(encoding="gb18030", errors="ignore")
# ///状态信息
l_dict["StatusMsg"] = pBatchOrderAction.StatusMsg.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pBatchOrderAction.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pBatchOrderAction.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pBatchOrderAction.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnOptionSelfClose(self, pOptionSelfClose):
'''
///期权自对冲通知
'''
self.PTP_Algos.DumpRspDict("T_OptionSelfClose",pOptionSelfClose)
l_dict={}
"""CThostFtdcOptionSelfCloseField
# ///经纪公司代码
l_dict["BrokerID"] = pOptionSelfClose.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pOptionSelfClose.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pOptionSelfClose.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///期权自对冲引用
l_dict["OptionSelfCloseRef"] = pOptionSelfClose.OptionSelfCloseRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pOptionSelfClose.UserID.decode(encoding="gb18030", errors="ignore")
# ///数量
l_dict["Volume"] = pOptionSelfClose.Volume
# ///请求编号
l_dict["RequestID"] = pOptionSelfClose.RequestID
# ///业务单元
l_dict["BusinessUnit"] = pOptionSelfClose.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pOptionSelfClose.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///期权行权的头寸是否自对冲
l_dict["OptSelfCloseFlag"] = pOptionSelfClose.OptSelfCloseFlag.decode(encoding="gb18030", errors="ignore")
# ///本地期权自对冲编号
l_dict["OptionSelfCloseLocalID"] = pOptionSelfClose.OptionSelfCloseLocalID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pOptionSelfClose.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pOptionSelfClose.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pOptionSelfClose.ClientID.decode(encoding="gb18030", errors="ignore")
# ///合约在交易所的代码
l_dict["ExchangeInstID"] = pOptionSelfClose.ExchangeInstID.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pOptionSelfClose.TraderID.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pOptionSelfClose.InstallID
# ///期权自对冲提交状态
l_dict["OrderSubmitStatus"] = pOptionSelfClose.OrderSubmitStatus.decode(encoding="gb18030", errors="ignore")
# ///报单提示序号
l_dict["NotifySequence"] = pOptionSelfClose.NotifySequence
# ///交易日
l_dict["TradingDay"] = pOptionSelfClose.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pOptionSelfClose.SettlementID
# ///期权自对冲编号
l_dict["OptionSelfCloseSysID"] = pOptionSelfClose.OptionSelfCloseSysID.decode(encoding="gb18030", errors="ignore")
# ///报单日期
l_dict["InsertDate"] = pOptionSelfClose.InsertDate.decode(encoding="gb18030", errors="ignore")
# ///插入时间
l_dict["InsertTime"] = pOptionSelfClose.InsertTime.decode(encoding="gb18030", errors="ignore")
# ///撤销时间
l_dict["CancelTime"] = pOptionSelfClose.CancelTime.decode(encoding="gb18030", errors="ignore")
# ///自对冲结果
l_dict["ExecResult"] = pOptionSelfClose.ExecResult.decode(encoding="gb18030", errors="ignore")
# ///结算会员编号
l_dict["ClearingPartID"] = pOptionSelfClose.ClearingPartID.decode(encoding="gb18030", errors="ignore")
# ///序号
l_dict["SequenceNo"] = pOptionSelfClose.SequenceNo
# ///前置编号
l_dict["FrontID"] = pOptionSelfClose.FrontID
# ///会话编号
l_dict["SessionID"] = pOptionSelfClose.SessionID
# ///用户端产品信息
l_dict["UserProductInfo"] = pOptionSelfClose.UserProductInfo.decode(encoding="gb18030", errors="ignore")
# ///状态信息
l_dict["StatusMsg"] = pOptionSelfClose.StatusMsg.decode(encoding="gb18030", errors="ignore")
# ///操作用户代码
l_dict["ActiveUserID"] = pOptionSelfClose.ActiveUserID.decode(encoding="gb18030", errors="ignore")
# ///经纪公司报单编号
l_dict["BrokerOptionSelfCloseSeq"] = pOptionSelfClose.BrokerOptionSelfCloseSeq
# ///营业部编号
l_dict["BranchID"] = pOptionSelfClose.BranchID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pOptionSelfClose.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///资金账号
l_dict["AccountID"] = pOptionSelfClose.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pOptionSelfClose.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pOptionSelfClose.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pOptionSelfClose.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnErrRtnOptionSelfCloseInsert(self, pInputOptionSelfClose, pRspInfo):
'''
///期权自对冲录入错误回报
'''
self.PTP_Algos.DumpRspDict("T_InputOptionSelfClose",pInputOptionSelfClose)
l_dict={}
"""CThostFtdcInputOptionSelfCloseField
# ///经纪公司代码
l_dict["BrokerID"] = pInputOptionSelfClose.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInputOptionSelfClose.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pInputOptionSelfClose.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///期权自对冲引用
l_dict["OptionSelfCloseRef"] = pInputOptionSelfClose.OptionSelfCloseRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pInputOptionSelfClose.UserID.decode(encoding="gb18030", errors="ignore")
# ///数量
l_dict["Volume"] = pInputOptionSelfClose.Volume
# ///请求编号
l_dict["RequestID"] = pInputOptionSelfClose.RequestID
# ///业务单元
l_dict["BusinessUnit"] = pInputOptionSelfClose.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pInputOptionSelfClose.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///期权行权的头寸是否自对冲
l_dict["OptSelfCloseFlag"] = pInputOptionSelfClose.OptSelfCloseFlag.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pInputOptionSelfClose.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInputOptionSelfClose.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///资金账号
l_dict["AccountID"] = pInputOptionSelfClose.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pInputOptionSelfClose.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///交易编码
l_dict["ClientID"] = pInputOptionSelfClose.ClientID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pInputOptionSelfClose.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pInputOptionSelfClose.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnErrRtnOptionSelfCloseAction(self, pOptionSelfCloseAction, pRspInfo):
'''
///期权自对冲操作错误回报
'''
self.PTP_Algos.DumpRspDict("T_OptionSelfCloseAction",pOptionSelfCloseAction)
l_dict={}
"""CThostFtdcOptionSelfCloseActionField
# ///经纪公司代码
l_dict["BrokerID"] = pOptionSelfCloseAction.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pOptionSelfCloseAction.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///期权自对冲操作引用
l_dict["OptionSelfCloseActionRef"] = pOptionSelfCloseAction.OptionSelfCloseActionRef
# ///期权自对冲引用
l_dict["OptionSelfCloseRef"] = pOptionSelfCloseAction.OptionSelfCloseRef.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pOptionSelfCloseAction.RequestID
# ///前置编号
l_dict["FrontID"] = pOptionSelfCloseAction.FrontID
# ///会话编号
l_dict["SessionID"] = pOptionSelfCloseAction.SessionID
# ///交易所代码
l_dict["ExchangeID"] = pOptionSelfCloseAction.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///期权自对冲操作编号
l_dict["OptionSelfCloseSysID"] = pOptionSelfCloseAction.OptionSelfCloseSysID.decode(encoding="gb18030", errors="ignore")
# ///操作标志
l_dict["ActionFlag"] = pOptionSelfCloseAction.ActionFlag.decode(encoding="gb18030", errors="ignore")
# ///操作日期
l_dict["ActionDate"] = pOptionSelfCloseAction.ActionDate.decode(encoding="gb18030", errors="ignore")
# ///操作时间
l_dict["ActionTime"] = pOptionSelfCloseAction.ActionTime.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pOptionSelfCloseAction.TraderID.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pOptionSelfCloseAction.InstallID
# ///本地期权自对冲编号
l_dict["OptionSelfCloseLocalID"] = pOptionSelfCloseAction.OptionSelfCloseLocalID.decode(encoding="gb18030", errors="ignore")
# ///操作本地编号
l_dict["ActionLocalID"] = pOptionSelfCloseAction.ActionLocalID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pOptionSelfCloseAction.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pOptionSelfCloseAction.ClientID.decode(encoding="gb18030", errors="ignore")
# ///业务单元
l_dict["BusinessUnit"] = pOptionSelfCloseAction.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///报单操作状态
l_dict["OrderActionStatus"] = pOptionSelfCloseAction.OrderActionStatus.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pOptionSelfCloseAction.UserID.decode(encoding="gb18030", errors="ignore")
# ///状态信息
l_dict["StatusMsg"] = pOptionSelfCloseAction.StatusMsg.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pOptionSelfCloseAction.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///营业部编号
l_dict["BranchID"] = pOptionSelfCloseAction.BranchID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pOptionSelfCloseAction.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pOptionSelfCloseAction.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pOptionSelfCloseAction.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnCombAction(self, pCombAction):
'''
///申请组合通知
'''
self.PTP_Algos.DumpRspDict("T_CombAction",pCombAction)
l_dict={}
"""CThostFtdcCombActionField
# ///经纪公司代码
l_dict["BrokerID"] = pCombAction.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pCombAction.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pCombAction.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///组合引用
l_dict["CombActionRef"] = pCombAction.CombActionRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pCombAction.UserID.decode(encoding="gb18030", errors="ignore")
# ///买卖方向
l_dict["Direction"] = pCombAction.Direction.decode(encoding="gb18030", errors="ignore")
# ///数量
l_dict["Volume"] = pCombAction.Volume
# ///组合指令方向
l_dict["CombDirection"] = pCombAction.CombDirection.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pCombAction.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///本地申请组合编号
l_dict["ActionLocalID"] = pCombAction.ActionLocalID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pCombAction.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///会员代码
l_dict["ParticipantID"] = pCombAction.ParticipantID.decode(encoding="gb18030", errors="ignore")
# ///客户代码
l_dict["ClientID"] = pCombAction.ClientID.decode(encoding="gb18030", errors="ignore")
# ///合约在交易所的代码
l_dict["ExchangeInstID"] = pCombAction.ExchangeInstID.decode(encoding="gb18030", errors="ignore")
# ///交易所交易员代码
l_dict["TraderID"] = pCombAction.TraderID.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pCombAction.InstallID
# ///组合状态
l_dict["ActionStatus"] = pCombAction.ActionStatus.decode(encoding="gb18030", errors="ignore")
# ///报单提示序号
l_dict["NotifySequence"] = pCombAction.NotifySequence
# ///交易日
l_dict["TradingDay"] = pCombAction.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///结算编号
l_dict["SettlementID"] = pCombAction.SettlementID
# ///序号
l_dict["SequenceNo"] = pCombAction.SequenceNo
# ///前置编号
l_dict["FrontID"] = pCombAction.FrontID
# ///会话编号
l_dict["SessionID"] = pCombAction.SessionID
# ///用户端产品信息
l_dict["UserProductInfo"] = pCombAction.UserProductInfo.decode(encoding="gb18030", errors="ignore")
# ///状态信息
l_dict["StatusMsg"] = pCombAction.StatusMsg.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pCombAction.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pCombAction.MacAddress.decode(encoding="gb18030", errors="ignore")
# ///组合编号
l_dict["ComTradeID"] = pCombAction.ComTradeID.decode(encoding="gb18030", errors="ignore")
# ///营业部编号
l_dict["BranchID"] = pCombAction.BranchID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pCombAction.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnErrRtnCombActionInsert(self, pInputCombAction, pRspInfo):
'''
///申请组合录入错误回报
'''
self.PTP_Algos.DumpRspDict("T_InputCombAction",pInputCombAction)
l_dict={}
"""CThostFtdcInputCombActionField
# ///经纪公司代码
l_dict["BrokerID"] = pInputCombAction.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pInputCombAction.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pInputCombAction.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///组合引用
l_dict["CombActionRef"] = pInputCombAction.CombActionRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pInputCombAction.UserID.decode(encoding="gb18030", errors="ignore")
# ///买卖方向
l_dict["Direction"] = pInputCombAction.Direction.decode(encoding="gb18030", errors="ignore")
# ///数量
l_dict["Volume"] = pInputCombAction.Volume
# ///组合指令方向
l_dict["CombDirection"] = pInputCombAction.CombDirection.decode(encoding="gb18030", errors="ignore")
# ///投机套保标志
l_dict["HedgeFlag"] = pInputCombAction.HedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pInputCombAction.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pInputCombAction.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pInputCombAction.MacAddress.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pInputCombAction.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryContractBank(self, pContractBank, pRspInfo, nRequestID, bIsLast):
'''
///请求查询签约银行响应
'''
if bIsLast == True:
self.req_call['QryContractBank'] = 1
self.PTP_Algos.DumpRspDict("T_ContractBank",pContractBank)
l_dict={}
"""CThostFtdcContractBankField
# ///经纪公司代码
l_dict["BrokerID"] = pContractBank.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pContractBank.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分中心代码
l_dict["BankBrchID"] = pContractBank.BankBrchID.decode(encoding="gb18030", errors="ignore")
# ///银行名称
l_dict["BankName"] = pContractBank.BankName.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryParkedOrder(self, pParkedOrder, pRspInfo, nRequestID, bIsLast):
'''
///请求查询预埋单响应
'''
if bIsLast == True:
self.req_call['QryParkedOrder'] = 1
self.PTP_Algos.DumpRspDict("T_ParkedOrder",pParkedOrder)
l_dict={}
"""CThostFtdcParkedOrderField
# ///经纪公司代码
l_dict["BrokerID"] = pParkedOrder.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pParkedOrder.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pParkedOrder.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///报单引用
l_dict["OrderRef"] = pParkedOrder.OrderRef.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pParkedOrder.UserID.decode(encoding="gb18030", errors="ignore")
# ///报单价格条件
l_dict["OrderPriceType"] = pParkedOrder.OrderPriceType.decode(encoding="gb18030", errors="ignore")
# ///买卖方向
l_dict["Direction"] = pParkedOrder.Direction.decode(encoding="gb18030", errors="ignore")
# ///组合开平标志
l_dict["CombOffsetFlag"] = pParkedOrder.CombOffsetFlag.decode(encoding="gb18030", errors="ignore")
# ///组合投机套保标志
l_dict["CombHedgeFlag"] = pParkedOrder.CombHedgeFlag.decode(encoding="gb18030", errors="ignore")
# ///价格
l_dict["LimitPrice"] = pParkedOrder.LimitPrice
# ///数量
l_dict["VolumeTotalOriginal"] = pParkedOrder.VolumeTotalOriginal
# ///有效期类型
l_dict["TimeCondition"] = pParkedOrder.TimeCondition.decode(encoding="gb18030", errors="ignore")
# ///GTD日期
l_dict["GTDDate"] = pParkedOrder.GTDDate.decode(encoding="gb18030", errors="ignore")
# ///成交量类型
l_dict["VolumeCondition"] = pParkedOrder.VolumeCondition.decode(encoding="gb18030", errors="ignore")
# ///最小成交量
l_dict["MinVolume"] = pParkedOrder.MinVolume
# ///触发条件
l_dict["ContingentCondition"] = pParkedOrder.ContingentCondition.decode(encoding="gb18030", errors="ignore")
# ///止损价
l_dict["StopPrice"] = pParkedOrder.StopPrice
# ///强平原因
l_dict["ForceCloseReason"] = pParkedOrder.ForceCloseReason.decode(encoding="gb18030", errors="ignore")
# ///自动挂起标志
l_dict["IsAutoSuspend"] = pParkedOrder.IsAutoSuspend
# ///业务单元
l_dict["BusinessUnit"] = pParkedOrder.BusinessUnit.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pParkedOrder.RequestID
# ///用户强评标志
l_dict["UserForceClose"] = pParkedOrder.UserForceClose
# ///交易所代码
l_dict["ExchangeID"] = pParkedOrder.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///预埋报单编号
l_dict["ParkedOrderID"] = pParkedOrder.ParkedOrderID.decode(encoding="gb18030", errors="ignore")
# ///用户类型
l_dict["UserType"] = pParkedOrder.UserType.decode(encoding="gb18030", errors="ignore")
# ///预埋单状态
l_dict["Status"] = pParkedOrder.Status.decode(encoding="gb18030", errors="ignore")
# ///错误代码
l_dict["ErrorID"] = pParkedOrder.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pParkedOrder.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///互换单标志
l_dict["IsSwapOrder"] = pParkedOrder.IsSwapOrder
# ///资金账号
l_dict["AccountID"] = pParkedOrder.AccountID.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pParkedOrder.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///交易编码
l_dict["ClientID"] = pParkedOrder.ClientID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pParkedOrder.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pParkedOrder.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pParkedOrder.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryParkedOrderAction(self, pParkedOrderAction, pRspInfo, nRequestID, bIsLast):
'''
///请求查询预埋撤单响应
'''
if bIsLast == True:
self.req_call['QryParkedOrderAction'] = 1
self.PTP_Algos.DumpRspDict("T_ParkedOrderAction",pParkedOrderAction)
l_dict={}
"""CThostFtdcParkedOrderActionField
# ///经纪公司代码
l_dict["BrokerID"] = pParkedOrderAction.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pParkedOrderAction.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///报单操作引用
l_dict["OrderActionRef"] = pParkedOrderAction.OrderActionRef
# ///报单引用
l_dict["OrderRef"] = pParkedOrderAction.OrderRef.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pParkedOrderAction.RequestID
# ///前置编号
l_dict["FrontID"] = pParkedOrderAction.FrontID
# ///会话编号
l_dict["SessionID"] = pParkedOrderAction.SessionID
# ///交易所代码
l_dict["ExchangeID"] = pParkedOrderAction.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///报单编号
l_dict["OrderSysID"] = pParkedOrderAction.OrderSysID.decode(encoding="gb18030", errors="ignore")
# ///操作标志
l_dict["ActionFlag"] = pParkedOrderAction.ActionFlag.decode(encoding="gb18030", errors="ignore")
# ///价格
l_dict["LimitPrice"] = pParkedOrderAction.LimitPrice
# ///数量变化
l_dict["VolumeChange"] = pParkedOrderAction.VolumeChange
# ///用户代码
l_dict["UserID"] = pParkedOrderAction.UserID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pParkedOrderAction.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///预埋撤单单编号
l_dict["ParkedOrderActionID"] = pParkedOrderAction.ParkedOrderActionID.decode(encoding="gb18030", errors="ignore")
# ///用户类型
l_dict["UserType"] = pParkedOrderAction.UserType.decode(encoding="gb18030", errors="ignore")
# ///预埋撤单状态
l_dict["Status"] = pParkedOrderAction.Status.decode(encoding="gb18030", errors="ignore")
# ///错误代码
l_dict["ErrorID"] = pParkedOrderAction.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pParkedOrderAction.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pParkedOrderAction.InvestUnitID.decode(encoding="gb18030", errors="ignore")
# ///IP地址
l_dict["IPAddress"] = pParkedOrderAction.IPAddress.decode(encoding="gb18030", errors="ignore")
# ///Mac地址
l_dict["MacAddress"] = pParkedOrderAction.MacAddress.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryTradingNotice(self, pTradingNotice, pRspInfo, nRequestID, bIsLast):
'''
///请求查询交易通知响应
'''
if bIsLast == True:
self.req_call['QryTradingNotice'] = 1
self.PTP_Algos.DumpRspDict("T_TradingNotice",pTradingNotice)
l_dict={}
"""CThostFtdcTradingNoticeField
# ///经纪公司代码
l_dict["BrokerID"] = pTradingNotice.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者范围
l_dict["InvestorRange"] = pTradingNotice.InvestorRange.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pTradingNotice.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///序列系列号
l_dict["SequenceSeries"] = pTradingNotice.SequenceSeries
# ///用户代码
l_dict["UserID"] = pTradingNotice.UserID.decode(encoding="gb18030", errors="ignore")
# ///发送时间
l_dict["SendTime"] = pTradingNotice.SendTime.decode(encoding="gb18030", errors="ignore")
# ///序列号
l_dict["SequenceNo"] = pTradingNotice.SequenceNo
# ///消息正文
l_dict["FieldContent"] = pTradingNotice.FieldContent.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pTradingNotice.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryBrokerTradingParams(self, pBrokerTradingParams, pRspInfo, nRequestID, bIsLast):
'''
///请求查询经纪公司交易参数响应
'''
if bIsLast == True:
self.req_call['QryBrokerTradingParams'] = 1
self.PTP_Algos.DumpRspDict("T_BrokerTradingParams",pBrokerTradingParams)
l_dict={}
"""CThostFtdcBrokerTradingParamsField
# ///经纪公司代码
l_dict["BrokerID"] = pBrokerTradingParams.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pBrokerTradingParams.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///保证金价格类型
l_dict["MarginPriceType"] = pBrokerTradingParams.MarginPriceType.decode(encoding="gb18030", errors="ignore")
# ///盈亏算法
l_dict["Algorithm"] = pBrokerTradingParams.Algorithm.decode(encoding="gb18030", errors="ignore")
# ///可用是否包含平仓盈利
l_dict["AvailIncludeCloseProfit"] = pBrokerTradingParams.AvailIncludeCloseProfit.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pBrokerTradingParams.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///期权权利金价格类型
l_dict["OptionRoyaltyPriceType"] = pBrokerTradingParams.OptionRoyaltyPriceType.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pBrokerTradingParams.AccountID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQryBrokerTradingAlgos(self, pBrokerTradingAlgos, pRspInfo, nRequestID, bIsLast):
'''
///请求查询经纪公司交易算法响应
'''
if bIsLast == True:
self.req_call['QryBrokerTradingAlgos'] = 1
self.PTP_Algos.DumpRspDict("T_BrokerTradingAlgos",pBrokerTradingAlgos)
l_dict={}
"""CThostFtdcBrokerTradingAlgosField
# ///经纪公司代码
l_dict["BrokerID"] = pBrokerTradingAlgos.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pBrokerTradingAlgos.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pBrokerTradingAlgos.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///持仓处理算法编号
l_dict["HandlePositionAlgoID"] = pBrokerTradingAlgos.HandlePositionAlgoID.decode(encoding="gb18030", errors="ignore")
# ///寻找保证金率算法编号
l_dict["FindMarginRateAlgoID"] = pBrokerTradingAlgos.FindMarginRateAlgoID.decode(encoding="gb18030", errors="ignore")
# ///资金处理算法编号
l_dict["HandleTradingAccountAlgoID" = pBrokerTradingAlgos.HandleTradingAccountAlgoID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQueryCFMMCTradingAccountToken(self, pQueryCFMMCTradingAccountToken, pRspInfo, nRequestID, bIsLast):
'''
///请求查询监控中心用户令牌
'''
if bIsLast == True:
self.req_call['QueryCFMMCTradingAccountToken'] = 1
self.PTP_Algos.DumpRspDict("T_QueryCFMMCTradingAccountToken",pQueryCFMMCTradingAccountToken)
l_dict={}
"""CThostFtdcQueryCFMMCTradingAccountTokenField
# ///经纪公司代码
l_dict["BrokerID"] = pQueryCFMMCTradingAccountToken.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///投资者代码
l_dict["InvestorID"] = pQueryCFMMCTradingAccountToken.InvestorID.decode(encoding="gb18030", errors="ignore")
# ///投资单元代码
l_dict["InvestUnitID"] = pQueryCFMMCTradingAccountToken.InvestUnitID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnFromBankToFutureByBank(self, pRspTransfer):
'''
///银行发起银行资金转期货通知
'''
self.PTP_Algos.DumpRspDict("T_RspTransfer",pRspTransfer)
l_dict={}
"""CThostFtdcRspTransferField
# ///业务功能码
l_dict["TradeCode"] = pRspTransfer.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pRspTransfer.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pRspTransfer.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pRspTransfer.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pRspTransfer.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pRspTransfer.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pRspTransfer.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pRspTransfer.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pRspTransfer.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pRspTransfer.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pRspTransfer.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pRspTransfer.SessionID
# ///客户姓名
l_dict["CustomerName"] = pRspTransfer.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pRspTransfer.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pRspTransfer.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pRspTransfer.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pRspTransfer.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pRspTransfer.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pRspTransfer.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pRspTransfer.Password.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pRspTransfer.InstallID
# ///期货公司流水号
l_dict["FutureSerial"] = pRspTransfer.FutureSerial
# ///用户标识
l_dict["UserID"] = pRspTransfer.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pRspTransfer.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pRspTransfer.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///转帐金额
l_dict["TradeAmount"] = pRspTransfer.TradeAmount
# ///期货可取金额
l_dict["FutureFetchAmount"] = pRspTransfer.FutureFetchAmount
# ///费用支付标志
l_dict["FeePayFlag"] = pRspTransfer.FeePayFlag.decode(encoding="gb18030", errors="ignore")
# ///应收客户费用
l_dict["CustFee"] = pRspTransfer.CustFee
# ///应收期货公司费用
l_dict["BrokerFee"] = pRspTransfer.BrokerFee
# ///发送方给接收方的消息
l_dict["Message"] = pRspTransfer.Message.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pRspTransfer.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pRspTransfer.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pRspTransfer.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pRspTransfer.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pRspTransfer.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pRspTransfer.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pRspTransfer.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pRspTransfer.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pRspTransfer.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pRspTransfer.RequestID
# ///交易ID
l_dict["TID"] = pRspTransfer.TID
# ///转账交易状态
l_dict["TransferStatus"] = pRspTransfer.TransferStatus.decode(encoding="gb18030", errors="ignore")
# ///错误代码
l_dict["ErrorID"] = pRspTransfer.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pRspTransfer.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pRspTransfer.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnFromFutureToBankByBank(self, pRspTransfer):
'''
///银行发起期货资金转银行通知
'''
self.PTP_Algos.DumpRspDict("T_RspTransfer",pRspTransfer)
l_dict={}
"""CThostFtdcRspTransferField
# ///业务功能码
l_dict["TradeCode"] = pRspTransfer.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pRspTransfer.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pRspTransfer.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pRspTransfer.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pRspTransfer.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pRspTransfer.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pRspTransfer.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pRspTransfer.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pRspTransfer.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pRspTransfer.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pRspTransfer.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pRspTransfer.SessionID
# ///客户姓名
l_dict["CustomerName"] = pRspTransfer.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pRspTransfer.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pRspTransfer.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pRspTransfer.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pRspTransfer.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pRspTransfer.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pRspTransfer.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pRspTransfer.Password.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pRspTransfer.InstallID
# ///期货公司流水号
l_dict["FutureSerial"] = pRspTransfer.FutureSerial
# ///用户标识
l_dict["UserID"] = pRspTransfer.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pRspTransfer.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pRspTransfer.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///转帐金额
l_dict["TradeAmount"] = pRspTransfer.TradeAmount
# ///期货可取金额
l_dict["FutureFetchAmount"] = pRspTransfer.FutureFetchAmount
# ///费用支付标志
l_dict["FeePayFlag"] = pRspTransfer.FeePayFlag.decode(encoding="gb18030", errors="ignore")
# ///应收客户费用
l_dict["CustFee"] = pRspTransfer.CustFee
# ///应收期货公司费用
l_dict["BrokerFee"] = pRspTransfer.BrokerFee
# ///发送方给接收方的消息
l_dict["Message"] = pRspTransfer.Message.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pRspTransfer.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pRspTransfer.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pRspTransfer.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pRspTransfer.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pRspTransfer.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pRspTransfer.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pRspTransfer.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pRspTransfer.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pRspTransfer.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pRspTransfer.RequestID
# ///交易ID
l_dict["TID"] = pRspTransfer.TID
# ///转账交易状态
l_dict["TransferStatus"] = pRspTransfer.TransferStatus.decode(encoding="gb18030", errors="ignore")
# ///错误代码
l_dict["ErrorID"] = pRspTransfer.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pRspTransfer.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pRspTransfer.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnRepealFromBankToFutureByBank(self, pRspRepeal):
'''
///银行发起冲正银行转期货通知
'''
self.PTP_Algos.DumpRspDict("T_RspRepeal",pRspRepeal)
l_dict={}
"""CThostFtdcRspRepealField
# ///冲正时间间隔
l_dict["RepealTimeInterval"] = pRspRepeal.RepealTimeInterval
# ///已经冲正次数
l_dict["RepealedTimes"] = pRspRepeal.RepealedTimes
# ///银行冲正标志
l_dict["BankRepealFlag"] = pRspRepeal.BankRepealFlag.decode(encoding="gb18030", errors="ignore")
# ///期商冲正标志
l_dict["BrokerRepealFlag"] = pRspRepeal.BrokerRepealFlag.decode(encoding="gb18030", errors="ignore")
# ///被冲正平台流水号
l_dict["PlateRepealSerial"] = pRspRepeal.PlateRepealSerial
# ///被冲正银行流水号
l_dict["BankRepealSerial"] = pRspRepeal.BankRepealSerial.decode(encoding="gb18030", errors="ignore")
# ///被冲正期货流水号
l_dict["FutureRepealSerial"] = pRspRepeal.FutureRepealSerial
# ///业务功能码
l_dict["TradeCode"] = pRspRepeal.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pRspRepeal.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pRspRepeal.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pRspRepeal.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pRspRepeal.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pRspRepeal.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pRspRepeal.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pRspRepeal.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pRspRepeal.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pRspRepeal.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pRspRepeal.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pRspRepeal.SessionID
# ///客户姓名
l_dict["CustomerName"] = pRspRepeal.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pRspRepeal.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pRspRepeal.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pRspRepeal.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pRspRepeal.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pRspRepeal.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pRspRepeal.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pRspRepeal.Password.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pRspRepeal.InstallID
# ///期货公司流水号
l_dict["FutureSerial"] = pRspRepeal.FutureSerial
# ///用户标识
l_dict["UserID"] = pRspRepeal.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pRspRepeal.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pRspRepeal.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///转帐金额
l_dict["TradeAmount"] = pRspRepeal.TradeAmount
# ///期货可取金额
l_dict["FutureFetchAmount"] = pRspRepeal.FutureFetchAmount
# ///费用支付标志
l_dict["FeePayFlag"] = pRspRepeal.FeePayFlag.decode(encoding="gb18030", errors="ignore")
# ///应收客户费用
l_dict["CustFee"] = pRspRepeal.CustFee
# ///应收期货公司费用
l_dict["BrokerFee"] = pRspRepeal.BrokerFee
# ///发送方给接收方的消息
l_dict["Message"] = pRspRepeal.Message.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pRspRepeal.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pRspRepeal.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pRspRepeal.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pRspRepeal.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pRspRepeal.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pRspRepeal.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pRspRepeal.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pRspRepeal.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pRspRepeal.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pRspRepeal.RequestID
# ///交易ID
l_dict["TID"] = pRspRepeal.TID
# ///转账交易状态
l_dict["TransferStatus"] = pRspRepeal.TransferStatus.decode(encoding="gb18030", errors="ignore")
# ///错误代码
l_dict["ErrorID"] = pRspRepeal.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pRspRepeal.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pRspRepeal.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnRepealFromFutureToBankByBank(self, pRspRepeal):
'''
///银行发起冲正期货转银行通知
'''
self.PTP_Algos.DumpRspDict("T_RspRepeal",pRspRepeal)
l_dict={}
"""CThostFtdcRspRepealField
# ///冲正时间间隔
l_dict["RepealTimeInterval"] = pRspRepeal.RepealTimeInterval
# ///已经冲正次数
l_dict["RepealedTimes"] = pRspRepeal.RepealedTimes
# ///银行冲正标志
l_dict["BankRepealFlag"] = pRspRepeal.BankRepealFlag.decode(encoding="gb18030", errors="ignore")
# ///期商冲正标志
l_dict["BrokerRepealFlag"] = pRspRepeal.BrokerRepealFlag.decode(encoding="gb18030", errors="ignore")
# ///被冲正平台流水号
l_dict["PlateRepealSerial"] = pRspRepeal.PlateRepealSerial
# ///被冲正银行流水号
l_dict["BankRepealSerial"] = pRspRepeal.BankRepealSerial.decode(encoding="gb18030", errors="ignore")
# ///被冲正期货流水号
l_dict["FutureRepealSerial"] = pRspRepeal.FutureRepealSerial
# ///业务功能码
l_dict["TradeCode"] = pRspRepeal.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pRspRepeal.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pRspRepeal.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pRspRepeal.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pRspRepeal.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pRspRepeal.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pRspRepeal.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pRspRepeal.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pRspRepeal.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pRspRepeal.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pRspRepeal.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pRspRepeal.SessionID
# ///客户姓名
l_dict["CustomerName"] = pRspRepeal.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pRspRepeal.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pRspRepeal.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pRspRepeal.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pRspRepeal.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pRspRepeal.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pRspRepeal.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pRspRepeal.Password.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pRspRepeal.InstallID
# ///期货公司流水号
l_dict["FutureSerial"] = pRspRepeal.FutureSerial
# ///用户标识
l_dict["UserID"] = pRspRepeal.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pRspRepeal.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pRspRepeal.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///转帐金额
l_dict["TradeAmount"] = pRspRepeal.TradeAmount
# ///期货可取金额
l_dict["FutureFetchAmount"] = pRspRepeal.FutureFetchAmount
# ///费用支付标志
l_dict["FeePayFlag"] = pRspRepeal.FeePayFlag.decode(encoding="gb18030", errors="ignore")
# ///应收客户费用
l_dict["CustFee"] = pRspRepeal.CustFee
# ///应收期货公司费用
l_dict["BrokerFee"] = pRspRepeal.BrokerFee
# ///发送方给接收方的消息
l_dict["Message"] = pRspRepeal.Message.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pRspRepeal.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pRspRepeal.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pRspRepeal.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pRspRepeal.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pRspRepeal.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pRspRepeal.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pRspRepeal.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pRspRepeal.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pRspRepeal.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pRspRepeal.RequestID
# ///交易ID
l_dict["TID"] = pRspRepeal.TID
# ///转账交易状态
l_dict["TransferStatus"] = pRspRepeal.TransferStatus.decode(encoding="gb18030", errors="ignore")
# ///错误代码
l_dict["ErrorID"] = pRspRepeal.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pRspRepeal.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pRspRepeal.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnFromBankToFutureByFuture(self, pRspTransfer):
'''
///期货发起银行资金转期货通知
'''
self.PTP_Algos.DumpRspDict("T_RspTransfer",pRspTransfer)
l_dict={}
"""CThostFtdcRspTransferField
# ///业务功能码
l_dict["TradeCode"] = pRspTransfer.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pRspTransfer.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pRspTransfer.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pRspTransfer.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pRspTransfer.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pRspTransfer.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pRspTransfer.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pRspTransfer.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pRspTransfer.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pRspTransfer.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pRspTransfer.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pRspTransfer.SessionID
# ///客户姓名
l_dict["CustomerName"] = pRspTransfer.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pRspTransfer.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pRspTransfer.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pRspTransfer.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pRspTransfer.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pRspTransfer.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pRspTransfer.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pRspTransfer.Password.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pRspTransfer.InstallID
# ///期货公司流水号
l_dict["FutureSerial"] = pRspTransfer.FutureSerial
# ///用户标识
l_dict["UserID"] = pRspTransfer.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pRspTransfer.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pRspTransfer.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///转帐金额
l_dict["TradeAmount"] = pRspTransfer.TradeAmount
# ///期货可取金额
l_dict["FutureFetchAmount"] = pRspTransfer.FutureFetchAmount
# ///费用支付标志
l_dict["FeePayFlag"] = pRspTransfer.FeePayFlag.decode(encoding="gb18030", errors="ignore")
# ///应收客户费用
l_dict["CustFee"] = pRspTransfer.CustFee
# ///应收期货公司费用
l_dict["BrokerFee"] = pRspTransfer.BrokerFee
# ///发送方给接收方的消息
l_dict["Message"] = pRspTransfer.Message.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pRspTransfer.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pRspTransfer.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pRspTransfer.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pRspTransfer.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pRspTransfer.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pRspTransfer.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pRspTransfer.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pRspTransfer.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pRspTransfer.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pRspTransfer.RequestID
# ///交易ID
l_dict["TID"] = pRspTransfer.TID
# ///转账交易状态
l_dict["TransferStatus"] = pRspTransfer.TransferStatus.decode(encoding="gb18030", errors="ignore")
# ///错误代码
l_dict["ErrorID"] = pRspTransfer.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pRspTransfer.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pRspTransfer.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnFromFutureToBankByFuture(self, pRspTransfer):
'''
///期货发起期货资金转银行通知
'''
self.PTP_Algos.DumpRspDict("T_RspTransfer",pRspTransfer)
l_dict={}
"""CThostFtdcRspTransferField
# ///业务功能码
l_dict["TradeCode"] = pRspTransfer.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pRspTransfer.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pRspTransfer.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pRspTransfer.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pRspTransfer.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pRspTransfer.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pRspTransfer.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pRspTransfer.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pRspTransfer.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pRspTransfer.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pRspTransfer.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pRspTransfer.SessionID
# ///客户姓名
l_dict["CustomerName"] = pRspTransfer.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pRspTransfer.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pRspTransfer.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pRspTransfer.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pRspTransfer.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pRspTransfer.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pRspTransfer.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pRspTransfer.Password.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pRspTransfer.InstallID
# ///期货公司流水号
l_dict["FutureSerial"] = pRspTransfer.FutureSerial
# ///用户标识
l_dict["UserID"] = pRspTransfer.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pRspTransfer.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pRspTransfer.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///转帐金额
l_dict["TradeAmount"] = pRspTransfer.TradeAmount
# ///期货可取金额
l_dict["FutureFetchAmount"] = pRspTransfer.FutureFetchAmount
# ///费用支付标志
l_dict["FeePayFlag"] = pRspTransfer.FeePayFlag.decode(encoding="gb18030", errors="ignore")
# ///应收客户费用
l_dict["CustFee"] = pRspTransfer.CustFee
# ///应收期货公司费用
l_dict["BrokerFee"] = pRspTransfer.BrokerFee
# ///发送方给接收方的消息
l_dict["Message"] = pRspTransfer.Message.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pRspTransfer.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pRspTransfer.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pRspTransfer.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pRspTransfer.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pRspTransfer.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pRspTransfer.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pRspTransfer.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pRspTransfer.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pRspTransfer.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pRspTransfer.RequestID
# ///交易ID
l_dict["TID"] = pRspTransfer.TID
# ///转账交易状态
l_dict["TransferStatus"] = pRspTransfer.TransferStatus.decode(encoding="gb18030", errors="ignore")
# ///错误代码
l_dict["ErrorID"] = pRspTransfer.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pRspTransfer.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pRspTransfer.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnRepealFromBankToFutureByFutureManual(self, pRspRepeal):
'''
///系统运行时期货端手工发起冲正银行转期货请求,银行处理完毕后报盘发回的通知
'''
self.PTP_Algos.DumpRspDict("T_RspRepeal",pRspRepeal)
l_dict={}
"""CThostFtdcRspRepealField
# ///冲正时间间隔
l_dict["RepealTimeInterval"] = pRspRepeal.RepealTimeInterval
# ///已经冲正次数
l_dict["RepealedTimes"] = pRspRepeal.RepealedTimes
# ///银行冲正标志
l_dict["BankRepealFlag"] = pRspRepeal.BankRepealFlag.decode(encoding="gb18030", errors="ignore")
# ///期商冲正标志
l_dict["BrokerRepealFlag"] = pRspRepeal.BrokerRepealFlag.decode(encoding="gb18030", errors="ignore")
# ///被冲正平台流水号
l_dict["PlateRepealSerial"] = pRspRepeal.PlateRepealSerial
# ///被冲正银行流水号
l_dict["BankRepealSerial"] = pRspRepeal.BankRepealSerial.decode(encoding="gb18030", errors="ignore")
# ///被冲正期货流水号
l_dict["FutureRepealSerial"] = pRspRepeal.FutureRepealSerial
# ///业务功能码
l_dict["TradeCode"] = pRspRepeal.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pRspRepeal.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pRspRepeal.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pRspRepeal.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pRspRepeal.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pRspRepeal.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pRspRepeal.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pRspRepeal.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pRspRepeal.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pRspRepeal.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pRspRepeal.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pRspRepeal.SessionID
# ///客户姓名
l_dict["CustomerName"] = pRspRepeal.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pRspRepeal.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pRspRepeal.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pRspRepeal.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pRspRepeal.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pRspRepeal.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pRspRepeal.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pRspRepeal.Password.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pRspRepeal.InstallID
# ///期货公司流水号
l_dict["FutureSerial"] = pRspRepeal.FutureSerial
# ///用户标识
l_dict["UserID"] = pRspRepeal.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pRspRepeal.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pRspRepeal.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///转帐金额
l_dict["TradeAmount"] = pRspRepeal.TradeAmount
# ///期货可取金额
l_dict["FutureFetchAmount"] = pRspRepeal.FutureFetchAmount
# ///费用支付标志
l_dict["FeePayFlag"] = pRspRepeal.FeePayFlag.decode(encoding="gb18030", errors="ignore")
# ///应收客户费用
l_dict["CustFee"] = pRspRepeal.CustFee
# ///应收期货公司费用
l_dict["BrokerFee"] = pRspRepeal.BrokerFee
# ///发送方给接收方的消息
l_dict["Message"] = pRspRepeal.Message.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pRspRepeal.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pRspRepeal.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pRspRepeal.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pRspRepeal.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pRspRepeal.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pRspRepeal.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pRspRepeal.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pRspRepeal.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pRspRepeal.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pRspRepeal.RequestID
# ///交易ID
l_dict["TID"] = pRspRepeal.TID
# ///转账交易状态
l_dict["TransferStatus"] = pRspRepeal.TransferStatus.decode(encoding="gb18030", errors="ignore")
# ///错误代码
l_dict["ErrorID"] = pRspRepeal.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pRspRepeal.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pRspRepeal.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnRepealFromFutureToBankByFutureManual(self, pRspRepeal):
'''
///系统运行时期货端手工发起冲正期货转银行请求,银行处理完毕后报盘发回的通知
'''
self.PTP_Algos.DumpRspDict("T_RspRepeal",pRspRepeal)
l_dict={}
"""CThostFtdcRspRepealField
# ///冲正时间间隔
l_dict["RepealTimeInterval"] = pRspRepeal.RepealTimeInterval
# ///已经冲正次数
l_dict["RepealedTimes"] = pRspRepeal.RepealedTimes
# ///银行冲正标志
l_dict["BankRepealFlag"] = pRspRepeal.BankRepealFlag.decode(encoding="gb18030", errors="ignore")
# ///期商冲正标志
l_dict["BrokerRepealFlag"] = pRspRepeal.BrokerRepealFlag.decode(encoding="gb18030", errors="ignore")
# ///被冲正平台流水号
l_dict["PlateRepealSerial"] = pRspRepeal.PlateRepealSerial
# ///被冲正银行流水号
l_dict["BankRepealSerial"] = pRspRepeal.BankRepealSerial.decode(encoding="gb18030", errors="ignore")
# ///被冲正期货流水号
l_dict["FutureRepealSerial"] = pRspRepeal.FutureRepealSerial
# ///业务功能码
l_dict["TradeCode"] = pRspRepeal.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pRspRepeal.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pRspRepeal.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pRspRepeal.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pRspRepeal.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pRspRepeal.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pRspRepeal.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pRspRepeal.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pRspRepeal.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pRspRepeal.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pRspRepeal.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pRspRepeal.SessionID
# ///客户姓名
l_dict["CustomerName"] = pRspRepeal.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pRspRepeal.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pRspRepeal.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pRspRepeal.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pRspRepeal.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pRspRepeal.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pRspRepeal.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pRspRepeal.Password.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pRspRepeal.InstallID
# ///期货公司流水号
l_dict["FutureSerial"] = pRspRepeal.FutureSerial
# ///用户标识
l_dict["UserID"] = pRspRepeal.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pRspRepeal.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pRspRepeal.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///转帐金额
l_dict["TradeAmount"] = pRspRepeal.TradeAmount
# ///期货可取金额
l_dict["FutureFetchAmount"] = pRspRepeal.FutureFetchAmount
# ///费用支付标志
l_dict["FeePayFlag"] = pRspRepeal.FeePayFlag.decode(encoding="gb18030", errors="ignore")
# ///应收客户费用
l_dict["CustFee"] = pRspRepeal.CustFee
# ///应收期货公司费用
l_dict["BrokerFee"] = pRspRepeal.BrokerFee
# ///发送方给接收方的消息
l_dict["Message"] = pRspRepeal.Message.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pRspRepeal.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pRspRepeal.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pRspRepeal.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pRspRepeal.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pRspRepeal.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pRspRepeal.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pRspRepeal.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pRspRepeal.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pRspRepeal.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pRspRepeal.RequestID
# ///交易ID
l_dict["TID"] = pRspRepeal.TID
# ///转账交易状态
l_dict["TransferStatus"] = pRspRepeal.TransferStatus.decode(encoding="gb18030", errors="ignore")
# ///错误代码
l_dict["ErrorID"] = pRspRepeal.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pRspRepeal.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pRspRepeal.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnQueryBankBalanceByFuture(self, pNotifyQueryAccount):
'''
///期货发起查询银行余额通知
'''
self.PTP_Algos.DumpRspDict("T_NotifyQueryAccount",pNotifyQueryAccount)
l_dict={}
"""CThostFtdcNotifyQueryAccountField
# ///业务功能码
l_dict["TradeCode"] = pNotifyQueryAccount.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pNotifyQueryAccount.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pNotifyQueryAccount.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pNotifyQueryAccount.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pNotifyQueryAccount.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pNotifyQueryAccount.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pNotifyQueryAccount.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pNotifyQueryAccount.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pNotifyQueryAccount.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pNotifyQueryAccount.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pNotifyQueryAccount.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pNotifyQueryAccount.SessionID
# ///客户姓名
l_dict["CustomerName"] = pNotifyQueryAccount.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pNotifyQueryAccount.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pNotifyQueryAccount.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pNotifyQueryAccount.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pNotifyQueryAccount.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pNotifyQueryAccount.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pNotifyQueryAccount.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pNotifyQueryAccount.Password.decode(encoding="gb18030", errors="ignore")
# ///期货公司流水号
l_dict["FutureSerial"] = pNotifyQueryAccount.FutureSerial
# ///安装编号
l_dict["InstallID"] = pNotifyQueryAccount.InstallID
# ///用户标识
l_dict["UserID"] = pNotifyQueryAccount.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pNotifyQueryAccount.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pNotifyQueryAccount.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pNotifyQueryAccount.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pNotifyQueryAccount.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pNotifyQueryAccount.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pNotifyQueryAccount.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pNotifyQueryAccount.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pNotifyQueryAccount.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pNotifyQueryAccount.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pNotifyQueryAccount.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pNotifyQueryAccount.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pNotifyQueryAccount.RequestID
# ///交易ID
l_dict["TID"] = pNotifyQueryAccount.TID
# ///银行可用金额
l_dict["BankUseAmount"] = pNotifyQueryAccount.BankUseAmount
# ///银行可取金额
l_dict["BankFetchAmount"] = pNotifyQueryAccount.BankFetchAmount
# ///错误代码
l_dict["ErrorID"] = pNotifyQueryAccount.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pNotifyQueryAccount.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pNotifyQueryAccount.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnErrRtnBankToFutureByFuture(self, pReqTransfer, pRspInfo):
'''
///期货发起银行资金转期货错误回报
'''
self.PTP_Algos.DumpRspDict("T_ReqTransfer",pReqTransfer)
l_dict={}
"""CThostFtdcReqTransferField
# ///业务功能码
l_dict["TradeCode"] = pReqTransfer.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pReqTransfer.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pReqTransfer.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pReqTransfer.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pReqTransfer.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pReqTransfer.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pReqTransfer.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pReqTransfer.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pReqTransfer.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pReqTransfer.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pReqTransfer.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pReqTransfer.SessionID
# ///客户姓名
l_dict["CustomerName"] = pReqTransfer.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pReqTransfer.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pReqTransfer.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pReqTransfer.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pReqTransfer.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pReqTransfer.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pReqTransfer.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pReqTransfer.Password.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pReqTransfer.InstallID
# ///期货公司流水号
l_dict["FutureSerial"] = pReqTransfer.FutureSerial
# ///用户标识
l_dict["UserID"] = pReqTransfer.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pReqTransfer.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pReqTransfer.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///转帐金额
l_dict["TradeAmount"] = pReqTransfer.TradeAmount
# ///期货可取金额
l_dict["FutureFetchAmount"] = pReqTransfer.FutureFetchAmount
# ///费用支付标志
l_dict["FeePayFlag"] = pReqTransfer.FeePayFlag.decode(encoding="gb18030", errors="ignore")
# ///应收客户费用
l_dict["CustFee"] = pReqTransfer.CustFee
# ///应收期货公司费用
l_dict["BrokerFee"] = pReqTransfer.BrokerFee
# ///发送方给接收方的消息
l_dict["Message"] = pReqTransfer.Message.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pReqTransfer.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pReqTransfer.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pReqTransfer.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pReqTransfer.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pReqTransfer.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pReqTransfer.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pReqTransfer.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pReqTransfer.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pReqTransfer.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pReqTransfer.RequestID
# ///交易ID
l_dict["TID"] = pReqTransfer.TID
# ///转账交易状态
l_dict["TransferStatus"] = pReqTransfer.TransferStatus.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pReqTransfer.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnErrRtnFutureToBankByFuture(self, pReqTransfer, pRspInfo):
'''
///期货发起期货资金转银行错误回报
'''
self.PTP_Algos.DumpRspDict("T_ReqTransfer",pReqTransfer)
l_dict={}
"""CThostFtdcReqTransferField
# ///业务功能码
l_dict["TradeCode"] = pReqTransfer.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pReqTransfer.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pReqTransfer.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pReqTransfer.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pReqTransfer.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pReqTransfer.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pReqTransfer.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pReqTransfer.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pReqTransfer.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pReqTransfer.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pReqTransfer.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pReqTransfer.SessionID
# ///客户姓名
l_dict["CustomerName"] = pReqTransfer.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pReqTransfer.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pReqTransfer.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pReqTransfer.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pReqTransfer.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pReqTransfer.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pReqTransfer.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pReqTransfer.Password.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pReqTransfer.InstallID
# ///期货公司流水号
l_dict["FutureSerial"] = pReqTransfer.FutureSerial
# ///用户标识
l_dict["UserID"] = pReqTransfer.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pReqTransfer.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pReqTransfer.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///转帐金额
l_dict["TradeAmount"] = pReqTransfer.TradeAmount
# ///期货可取金额
l_dict["FutureFetchAmount"] = pReqTransfer.FutureFetchAmount
# ///费用支付标志
l_dict["FeePayFlag"] = pReqTransfer.FeePayFlag.decode(encoding="gb18030", errors="ignore")
# ///应收客户费用
l_dict["CustFee"] = pReqTransfer.CustFee
# ///应收期货公司费用
l_dict["BrokerFee"] = pReqTransfer.BrokerFee
# ///发送方给接收方的消息
l_dict["Message"] = pReqTransfer.Message.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pReqTransfer.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pReqTransfer.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pReqTransfer.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pReqTransfer.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pReqTransfer.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pReqTransfer.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pReqTransfer.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pReqTransfer.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pReqTransfer.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pReqTransfer.RequestID
# ///交易ID
l_dict["TID"] = pReqTransfer.TID
# ///转账交易状态
l_dict["TransferStatus"] = pReqTransfer.TransferStatus.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pReqTransfer.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnErrRtnRepealBankToFutureByFutureManual(self, pReqRepeal, pRspInfo):
'''
///系统运行时期货端手工发起冲正银行转期货错误回报
'''
self.PTP_Algos.DumpRspDict("T_ReqRepeal",pReqRepeal)
l_dict={}
"""CThostFtdcReqRepealField
# ///冲正时间间隔
l_dict["RepealTimeInterval"] = pReqRepeal.RepealTimeInterval
# ///已经冲正次数
l_dict["RepealedTimes"] = pReqRepeal.RepealedTimes
# ///银行冲正标志
l_dict["BankRepealFlag"] = pReqRepeal.BankRepealFlag.decode(encoding="gb18030", errors="ignore")
# ///期商冲正标志
l_dict["BrokerRepealFlag"] = pReqRepeal.BrokerRepealFlag.decode(encoding="gb18030", errors="ignore")
# ///被冲正平台流水号
l_dict["PlateRepealSerial"] = pReqRepeal.PlateRepealSerial
# ///被冲正银行流水号
l_dict["BankRepealSerial"] = pReqRepeal.BankRepealSerial.decode(encoding="gb18030", errors="ignore")
# ///被冲正期货流水号
l_dict["FutureRepealSerial"] = pReqRepeal.FutureRepealSerial
# ///业务功能码
l_dict["TradeCode"] = pReqRepeal.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pReqRepeal.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pReqRepeal.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pReqRepeal.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pReqRepeal.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pReqRepeal.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pReqRepeal.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pReqRepeal.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pReqRepeal.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pReqRepeal.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pReqRepeal.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pReqRepeal.SessionID
# ///客户姓名
l_dict["CustomerName"] = pReqRepeal.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pReqRepeal.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pReqRepeal.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pReqRepeal.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pReqRepeal.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pReqRepeal.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pReqRepeal.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pReqRepeal.Password.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pReqRepeal.InstallID
# ///期货公司流水号
l_dict["FutureSerial"] = pReqRepeal.FutureSerial
# ///用户标识
l_dict["UserID"] = pReqRepeal.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pReqRepeal.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pReqRepeal.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///转帐金额
l_dict["TradeAmount"] = pReqRepeal.TradeAmount
# ///期货可取金额
l_dict["FutureFetchAmount"] = pReqRepeal.FutureFetchAmount
# ///费用支付标志
l_dict["FeePayFlag"] = pReqRepeal.FeePayFlag.decode(encoding="gb18030", errors="ignore")
# ///应收客户费用
l_dict["CustFee"] = pReqRepeal.CustFee
# ///应收期货公司费用
l_dict["BrokerFee"] = pReqRepeal.BrokerFee
# ///发送方给接收方的消息
l_dict["Message"] = pReqRepeal.Message.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pReqRepeal.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pReqRepeal.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pReqRepeal.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pReqRepeal.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pReqRepeal.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pReqRepeal.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pReqRepeal.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pReqRepeal.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pReqRepeal.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pReqRepeal.RequestID
# ///交易ID
l_dict["TID"] = pReqRepeal.TID
# ///转账交易状态
l_dict["TransferStatus"] = pReqRepeal.TransferStatus.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pReqRepeal.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnErrRtnRepealFutureToBankByFutureManual(self, pReqRepeal, pRspInfo):
'''
///系统运行时期货端手工发起冲正期货转银行错误回报
'''
self.PTP_Algos.DumpRspDict("T_ReqRepeal",pReqRepeal)
l_dict={}
"""CThostFtdcReqRepealField
# ///冲正时间间隔
l_dict["RepealTimeInterval"] = pReqRepeal.RepealTimeInterval
# ///已经冲正次数
l_dict["RepealedTimes"] = pReqRepeal.RepealedTimes
# ///银行冲正标志
l_dict["BankRepealFlag"] = pReqRepeal.BankRepealFlag.decode(encoding="gb18030", errors="ignore")
# ///期商冲正标志
l_dict["BrokerRepealFlag"] = pReqRepeal.BrokerRepealFlag.decode(encoding="gb18030", errors="ignore")
# ///被冲正平台流水号
l_dict["PlateRepealSerial"] = pReqRepeal.PlateRepealSerial
# ///被冲正银行流水号
l_dict["BankRepealSerial"] = pReqRepeal.BankRepealSerial.decode(encoding="gb18030", errors="ignore")
# ///被冲正期货流水号
l_dict["FutureRepealSerial"] = pReqRepeal.FutureRepealSerial
# ///业务功能码
l_dict["TradeCode"] = pReqRepeal.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pReqRepeal.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pReqRepeal.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pReqRepeal.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pReqRepeal.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pReqRepeal.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pReqRepeal.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pReqRepeal.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pReqRepeal.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pReqRepeal.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pReqRepeal.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pReqRepeal.SessionID
# ///客户姓名
l_dict["CustomerName"] = pReqRepeal.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pReqRepeal.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pReqRepeal.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pReqRepeal.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pReqRepeal.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pReqRepeal.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pReqRepeal.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pReqRepeal.Password.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pReqRepeal.InstallID
# ///期货公司流水号
l_dict["FutureSerial"] = pReqRepeal.FutureSerial
# ///用户标识
l_dict["UserID"] = pReqRepeal.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pReqRepeal.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pReqRepeal.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///转帐金额
l_dict["TradeAmount"] = pReqRepeal.TradeAmount
# ///期货可取金额
l_dict["FutureFetchAmount"] = pReqRepeal.FutureFetchAmount
# ///费用支付标志
l_dict["FeePayFlag"] = pReqRepeal.FeePayFlag.decode(encoding="gb18030", errors="ignore")
# ///应收客户费用
l_dict["CustFee"] = pReqRepeal.CustFee
# ///应收期货公司费用
l_dict["BrokerFee"] = pReqRepeal.BrokerFee
# ///发送方给接收方的消息
l_dict["Message"] = pReqRepeal.Message.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pReqRepeal.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pReqRepeal.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pReqRepeal.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pReqRepeal.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pReqRepeal.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pReqRepeal.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pReqRepeal.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pReqRepeal.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pReqRepeal.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pReqRepeal.RequestID
# ///交易ID
l_dict["TID"] = pReqRepeal.TID
# ///转账交易状态
l_dict["TransferStatus"] = pReqRepeal.TransferStatus.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pReqRepeal.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnErrRtnQueryBankBalanceByFuture(self, pReqQueryAccount, pRspInfo):
'''
///期货发起查询银行余额错误回报
'''
self.PTP_Algos.DumpRspDict("T_ReqQueryAccount",pReqQueryAccount)
l_dict={}
"""CThostFtdcReqQueryAccountField
# ///业务功能码
l_dict["TradeCode"] = pReqQueryAccount.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pReqQueryAccount.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pReqQueryAccount.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pReqQueryAccount.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pReqQueryAccount.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pReqQueryAccount.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pReqQueryAccount.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pReqQueryAccount.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pReqQueryAccount.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pReqQueryAccount.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pReqQueryAccount.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pReqQueryAccount.SessionID
# ///客户姓名
l_dict["CustomerName"] = pReqQueryAccount.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pReqQueryAccount.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pReqQueryAccount.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pReqQueryAccount.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pReqQueryAccount.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pReqQueryAccount.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pReqQueryAccount.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pReqQueryAccount.Password.decode(encoding="gb18030", errors="ignore")
# ///期货公司流水号
l_dict["FutureSerial"] = pReqQueryAccount.FutureSerial
# ///安装编号
l_dict["InstallID"] = pReqQueryAccount.InstallID
# ///用户标识
l_dict["UserID"] = pReqQueryAccount.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pReqQueryAccount.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pReqQueryAccount.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pReqQueryAccount.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pReqQueryAccount.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pReqQueryAccount.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pReqQueryAccount.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pReqQueryAccount.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pReqQueryAccount.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pReqQueryAccount.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pReqQueryAccount.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pReqQueryAccount.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pReqQueryAccount.RequestID
# ///交易ID
l_dict["TID"] = pReqQueryAccount.TID
# ///长客户姓名
l_dict["LongCustomerName"] = pReqQueryAccount.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnRepealFromBankToFutureByFuture(self, pRspRepeal):
'''
///期货发起冲正银行转期货请求,银行处理完毕后报盘发回的通知
'''
self.PTP_Algos.DumpRspDict("T_RspRepeal",pRspRepeal)
l_dict={}
"""CThostFtdcRspRepealField
# ///冲正时间间隔
l_dict["RepealTimeInterval"] = pRspRepeal.RepealTimeInterval
# ///已经冲正次数
l_dict["RepealedTimes"] = pRspRepeal.RepealedTimes
# ///银行冲正标志
l_dict["BankRepealFlag"] = pRspRepeal.BankRepealFlag.decode(encoding="gb18030", errors="ignore")
# ///期商冲正标志
l_dict["BrokerRepealFlag"] = pRspRepeal.BrokerRepealFlag.decode(encoding="gb18030", errors="ignore")
# ///被冲正平台流水号
l_dict["PlateRepealSerial"] = pRspRepeal.PlateRepealSerial
# ///被冲正银行流水号
l_dict["BankRepealSerial"] = pRspRepeal.BankRepealSerial.decode(encoding="gb18030", errors="ignore")
# ///被冲正期货流水号
l_dict["FutureRepealSerial"] = pRspRepeal.FutureRepealSerial
# ///业务功能码
l_dict["TradeCode"] = pRspRepeal.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pRspRepeal.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pRspRepeal.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pRspRepeal.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pRspRepeal.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pRspRepeal.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pRspRepeal.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pRspRepeal.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pRspRepeal.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pRspRepeal.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pRspRepeal.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pRspRepeal.SessionID
# ///客户姓名
l_dict["CustomerName"] = pRspRepeal.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pRspRepeal.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pRspRepeal.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pRspRepeal.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pRspRepeal.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pRspRepeal.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pRspRepeal.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pRspRepeal.Password.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pRspRepeal.InstallID
# ///期货公司流水号
l_dict["FutureSerial"] = pRspRepeal.FutureSerial
# ///用户标识
l_dict["UserID"] = pRspRepeal.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pRspRepeal.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pRspRepeal.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///转帐金额
l_dict["TradeAmount"] = pRspRepeal.TradeAmount
# ///期货可取金额
l_dict["FutureFetchAmount"] = pRspRepeal.FutureFetchAmount
# ///费用支付标志
l_dict["FeePayFlag"] = pRspRepeal.FeePayFlag.decode(encoding="gb18030", errors="ignore")
# ///应收客户费用
l_dict["CustFee"] = pRspRepeal.CustFee
# ///应收期货公司费用
l_dict["BrokerFee"] = pRspRepeal.BrokerFee
# ///发送方给接收方的消息
l_dict["Message"] = pRspRepeal.Message.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pRspRepeal.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pRspRepeal.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pRspRepeal.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pRspRepeal.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pRspRepeal.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pRspRepeal.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pRspRepeal.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pRspRepeal.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pRspRepeal.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pRspRepeal.RequestID
# ///交易ID
l_dict["TID"] = pRspRepeal.TID
# ///转账交易状态
l_dict["TransferStatus"] = pRspRepeal.TransferStatus.decode(encoding="gb18030", errors="ignore")
# ///错误代码
l_dict["ErrorID"] = pRspRepeal.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pRspRepeal.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pRspRepeal.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnRepealFromFutureToBankByFuture(self, pRspRepeal):
'''
///期货发起冲正期货转银行请求,银行处理完毕后报盘发回的通知
'''
self.PTP_Algos.DumpRspDict("T_RspRepeal",pRspRepeal)
l_dict={}
"""CThostFtdcRspRepealField
# ///冲正时间间隔
l_dict["RepealTimeInterval"] = pRspRepeal.RepealTimeInterval
# ///已经冲正次数
l_dict["RepealedTimes"] = pRspRepeal.RepealedTimes
# ///银行冲正标志
l_dict["BankRepealFlag"] = pRspRepeal.BankRepealFlag.decode(encoding="gb18030", errors="ignore")
# ///期商冲正标志
l_dict["BrokerRepealFlag"] = pRspRepeal.BrokerRepealFlag.decode(encoding="gb18030", errors="ignore")
# ///被冲正平台流水号
l_dict["PlateRepealSerial"] = pRspRepeal.PlateRepealSerial
# ///被冲正银行流水号
l_dict["BankRepealSerial"] = pRspRepeal.BankRepealSerial.decode(encoding="gb18030", errors="ignore")
# ///被冲正期货流水号
l_dict["FutureRepealSerial"] = pRspRepeal.FutureRepealSerial
# ///业务功能码
l_dict["TradeCode"] = pRspRepeal.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pRspRepeal.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pRspRepeal.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pRspRepeal.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pRspRepeal.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pRspRepeal.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pRspRepeal.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pRspRepeal.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pRspRepeal.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pRspRepeal.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pRspRepeal.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pRspRepeal.SessionID
# ///客户姓名
l_dict["CustomerName"] = pRspRepeal.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pRspRepeal.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pRspRepeal.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pRspRepeal.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pRspRepeal.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pRspRepeal.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pRspRepeal.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pRspRepeal.Password.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pRspRepeal.InstallID
# ///期货公司流水号
l_dict["FutureSerial"] = pRspRepeal.FutureSerial
# ///用户标识
l_dict["UserID"] = pRspRepeal.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pRspRepeal.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pRspRepeal.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///转帐金额
l_dict["TradeAmount"] = pRspRepeal.TradeAmount
# ///期货可取金额
l_dict["FutureFetchAmount"] = pRspRepeal.FutureFetchAmount
# ///费用支付标志
l_dict["FeePayFlag"] = pRspRepeal.FeePayFlag.decode(encoding="gb18030", errors="ignore")
# ///应收客户费用
l_dict["CustFee"] = pRspRepeal.CustFee
# ///应收期货公司费用
l_dict["BrokerFee"] = pRspRepeal.BrokerFee
# ///发送方给接收方的消息
l_dict["Message"] = pRspRepeal.Message.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pRspRepeal.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pRspRepeal.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pRspRepeal.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pRspRepeal.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pRspRepeal.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pRspRepeal.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pRspRepeal.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pRspRepeal.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pRspRepeal.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pRspRepeal.RequestID
# ///交易ID
l_dict["TID"] = pRspRepeal.TID
# ///转账交易状态
l_dict["TransferStatus"] = pRspRepeal.TransferStatus.decode(encoding="gb18030", errors="ignore")
# ///错误代码
l_dict["ErrorID"] = pRspRepeal.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pRspRepeal.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pRspRepeal.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspFromBankToFutureByFuture(self, pReqTransfer, pRspInfo, nRequestID, bIsLast):
'''
///期货发起银行资金转期货应答
'''
if bIsLast == True:
self.req_call['FromBankToFutureByFuture'] = 1
self.PTP_Algos.DumpRspDict("T_ReqTransfer",pReqTransfer)
l_dict={}
"""CThostFtdcReqTransferField
# ///业务功能码
l_dict["TradeCode"] = pReqTransfer.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pReqTransfer.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pReqTransfer.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pReqTransfer.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pReqTransfer.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pReqTransfer.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pReqTransfer.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pReqTransfer.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pReqTransfer.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pReqTransfer.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pReqTransfer.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pReqTransfer.SessionID
# ///客户姓名
l_dict["CustomerName"] = pReqTransfer.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pReqTransfer.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pReqTransfer.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pReqTransfer.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pReqTransfer.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pReqTransfer.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pReqTransfer.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pReqTransfer.Password.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pReqTransfer.InstallID
# ///期货公司流水号
l_dict["FutureSerial"] = pReqTransfer.FutureSerial
# ///用户标识
l_dict["UserID"] = pReqTransfer.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pReqTransfer.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pReqTransfer.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///转帐金额
l_dict["TradeAmount"] = pReqTransfer.TradeAmount
# ///期货可取金额
l_dict["FutureFetchAmount"] = pReqTransfer.FutureFetchAmount
# ///费用支付标志
l_dict["FeePayFlag"] = pReqTransfer.FeePayFlag.decode(encoding="gb18030", errors="ignore")
# ///应收客户费用
l_dict["CustFee"] = pReqTransfer.CustFee
# ///应收期货公司费用
l_dict["BrokerFee"] = pReqTransfer.BrokerFee
# ///发送方给接收方的消息
l_dict["Message"] = pReqTransfer.Message.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pReqTransfer.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pReqTransfer.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pReqTransfer.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pReqTransfer.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pReqTransfer.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pReqTransfer.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pReqTransfer.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pReqTransfer.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pReqTransfer.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pReqTransfer.RequestID
# ///交易ID
l_dict["TID"] = pReqTransfer.TID
# ///转账交易状态
l_dict["TransferStatus"] = pReqTransfer.TransferStatus.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pReqTransfer.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspFromFutureToBankByFuture(self, pReqTransfer, pRspInfo, nRequestID, bIsLast):
'''
///期货发起期货资金转银行应答
'''
if bIsLast == True:
self.req_call['FromFutureToBankByFuture'] = 1
self.PTP_Algos.DumpRspDict("T_ReqTransfer",pReqTransfer)
l_dict={}
"""CThostFtdcReqTransferField
# ///业务功能码
l_dict["TradeCode"] = pReqTransfer.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pReqTransfer.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pReqTransfer.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pReqTransfer.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pReqTransfer.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pReqTransfer.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pReqTransfer.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pReqTransfer.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pReqTransfer.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pReqTransfer.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pReqTransfer.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pReqTransfer.SessionID
# ///客户姓名
l_dict["CustomerName"] = pReqTransfer.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pReqTransfer.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pReqTransfer.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pReqTransfer.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pReqTransfer.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pReqTransfer.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pReqTransfer.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pReqTransfer.Password.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pReqTransfer.InstallID
# ///期货公司流水号
l_dict["FutureSerial"] = pReqTransfer.FutureSerial
# ///用户标识
l_dict["UserID"] = pReqTransfer.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pReqTransfer.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pReqTransfer.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///转帐金额
l_dict["TradeAmount"] = pReqTransfer.TradeAmount
# ///期货可取金额
l_dict["FutureFetchAmount"] = pReqTransfer.FutureFetchAmount
# ///费用支付标志
l_dict["FeePayFlag"] = pReqTransfer.FeePayFlag.decode(encoding="gb18030", errors="ignore")
# ///应收客户费用
l_dict["CustFee"] = pReqTransfer.CustFee
# ///应收期货公司费用
l_dict["BrokerFee"] = pReqTransfer.BrokerFee
# ///发送方给接收方的消息
l_dict["Message"] = pReqTransfer.Message.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pReqTransfer.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pReqTransfer.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pReqTransfer.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pReqTransfer.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pReqTransfer.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pReqTransfer.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pReqTransfer.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pReqTransfer.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pReqTransfer.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pReqTransfer.RequestID
# ///交易ID
l_dict["TID"] = pReqTransfer.TID
# ///转账交易状态
l_dict["TransferStatus"] = pReqTransfer.TransferStatus.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pReqTransfer.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspQueryBankAccountMoneyByFuture(self, pReqQueryAccount, pRspInfo, nRequestID, bIsLast):
'''
///期货发起查询银行余额应答
'''
if bIsLast == True:
self.req_call['QueryBankAccountMoneyByFuture'] = 1
self.PTP_Algos.DumpRspDict("T_ReqQueryAccount",pReqQueryAccount)
l_dict={}
"""CThostFtdcReqQueryAccountField
# ///业务功能码
l_dict["TradeCode"] = pReqQueryAccount.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pReqQueryAccount.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pReqQueryAccount.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pReqQueryAccount.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pReqQueryAccount.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pReqQueryAccount.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pReqQueryAccount.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pReqQueryAccount.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pReqQueryAccount.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pReqQueryAccount.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pReqQueryAccount.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pReqQueryAccount.SessionID
# ///客户姓名
l_dict["CustomerName"] = pReqQueryAccount.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pReqQueryAccount.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pReqQueryAccount.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pReqQueryAccount.CustType.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pReqQueryAccount.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pReqQueryAccount.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pReqQueryAccount.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pReqQueryAccount.Password.decode(encoding="gb18030", errors="ignore")
# ///期货公司流水号
l_dict["FutureSerial"] = pReqQueryAccount.FutureSerial
# ///安装编号
l_dict["InstallID"] = pReqQueryAccount.InstallID
# ///用户标识
l_dict["UserID"] = pReqQueryAccount.UserID.decode(encoding="gb18030", errors="ignore")
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pReqQueryAccount.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pReqQueryAccount.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pReqQueryAccount.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pReqQueryAccount.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pReqQueryAccount.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pReqQueryAccount.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pReqQueryAccount.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pReqQueryAccount.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pReqQueryAccount.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pReqQueryAccount.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pReqQueryAccount.OperNo.decode(encoding="gb18030", errors="ignore")
# ///请求编号
l_dict["RequestID"] = pReqQueryAccount.RequestID
# ///交易ID
l_dict["TID"] = pReqQueryAccount.TID
# ///长客户姓名
l_dict["LongCustomerName"] = pReqQueryAccount.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnOpenAccountByBank(self, pOpenAccount):
'''
///银行发起银期开户通知
'''
self.PTP_Algos.DumpRspDict("T_OpenAccount",pOpenAccount)
l_dict={}
"""CThostFtdcOpenAccountField
# ///业务功能码
l_dict["TradeCode"] = pOpenAccount.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pOpenAccount.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pOpenAccount.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pOpenAccount.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pOpenAccount.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pOpenAccount.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pOpenAccount.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pOpenAccount.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pOpenAccount.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pOpenAccount.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pOpenAccount.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pOpenAccount.SessionID
# ///客户姓名
l_dict["CustomerName"] = pOpenAccount.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pOpenAccount.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pOpenAccount.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///性别
l_dict["Gender"] = pOpenAccount.Gender.decode(encoding="gb18030", errors="ignore")
# ///国家代码
l_dict["CountryCode"] = pOpenAccount.CountryCode.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pOpenAccount.CustType.decode(encoding="gb18030", errors="ignore")
# ///地址
l_dict["Address"] = pOpenAccount.Address.decode(encoding="gb18030", errors="ignore")
# ///邮编
l_dict["ZipCode"] = pOpenAccount.ZipCode.decode(encoding="gb18030", errors="ignore")
# ///电话号码
l_dict["Telephone"] = pOpenAccount.Telephone.decode(encoding="gb18030", errors="ignore")
# ///手机
l_dict["MobilePhone"] = pOpenAccount.MobilePhone.decode(encoding="gb18030", errors="ignore")
# ///传真
l_dict["Fax"] = pOpenAccount.Fax.decode(encoding="gb18030", errors="ignore")
# ///电子邮件
l_dict["EMail"] = pOpenAccount.EMail.decode(encoding="gb18030", errors="ignore")
# ///资金账户状态
l_dict["MoneyAccountStatus"] = pOpenAccount.MoneyAccountStatus.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pOpenAccount.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pOpenAccount.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pOpenAccount.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pOpenAccount.Password.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pOpenAccount.InstallID
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pOpenAccount.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pOpenAccount.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///汇钞标志
l_dict["CashExchangeCode"] = pOpenAccount.CashExchangeCode.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pOpenAccount.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pOpenAccount.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pOpenAccount.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pOpenAccount.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pOpenAccount.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pOpenAccount.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pOpenAccount.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pOpenAccount.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pOpenAccount.OperNo.decode(encoding="gb18030", errors="ignore")
# ///交易ID
l_dict["TID"] = pOpenAccount.TID
# ///用户标识
l_dict["UserID"] = pOpenAccount.UserID.decode(encoding="gb18030", errors="ignore")
# ///错误代码
l_dict["ErrorID"] = pOpenAccount.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pOpenAccount.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pOpenAccount.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnCancelAccountByBank(self, pCancelAccount):
'''
///银行发起银期销户通知
'''
self.PTP_Algos.DumpRspDict("T_CancelAccount",pCancelAccount)
l_dict={}
"""CThostFtdcCancelAccountField
# ///业务功能码
l_dict["TradeCode"] = pCancelAccount.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pCancelAccount.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pCancelAccount.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pCancelAccount.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pCancelAccount.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pCancelAccount.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pCancelAccount.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pCancelAccount.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pCancelAccount.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pCancelAccount.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pCancelAccount.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pCancelAccount.SessionID
# ///客户姓名
l_dict["CustomerName"] = pCancelAccount.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pCancelAccount.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pCancelAccount.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///性别
l_dict["Gender"] = pCancelAccount.Gender.decode(encoding="gb18030", errors="ignore")
# ///国家代码
l_dict["CountryCode"] = pCancelAccount.CountryCode.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pCancelAccount.CustType.decode(encoding="gb18030", errors="ignore")
# ///地址
l_dict["Address"] = pCancelAccount.Address.decode(encoding="gb18030", errors="ignore")
# ///邮编
l_dict["ZipCode"] = pCancelAccount.ZipCode.decode(encoding="gb18030", errors="ignore")
# ///电话号码
l_dict["Telephone"] = pCancelAccount.Telephone.decode(encoding="gb18030", errors="ignore")
# ///手机
l_dict["MobilePhone"] = pCancelAccount.MobilePhone.decode(encoding="gb18030", errors="ignore")
# ///传真
l_dict["Fax"] = pCancelAccount.Fax.decode(encoding="gb18030", errors="ignore")
# ///电子邮件
l_dict["EMail"] = pCancelAccount.EMail.decode(encoding="gb18030", errors="ignore")
# ///资金账户状态
l_dict["MoneyAccountStatus"] = pCancelAccount.MoneyAccountStatus.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pCancelAccount.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pCancelAccount.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pCancelAccount.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pCancelAccount.Password.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pCancelAccount.InstallID
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pCancelAccount.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pCancelAccount.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///汇钞标志
l_dict["CashExchangeCode"] = pCancelAccount.CashExchangeCode.decode(encoding="gb18030", errors="ignore")
# ///摘要
l_dict["Digest"] = pCancelAccount.Digest.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pCancelAccount.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///渠道标志
l_dict["DeviceID"] = pCancelAccount.DeviceID.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号类型
l_dict["BankSecuAccType"] = pCancelAccount.BankSecuAccType.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pCancelAccount.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///期货单位帐号
l_dict["BankSecuAcc"] = pCancelAccount.BankSecuAcc.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pCancelAccount.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pCancelAccount.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易柜员
l_dict["OperNo"] = pCancelAccount.OperNo.decode(encoding="gb18030", errors="ignore")
# ///交易ID
l_dict["TID"] = pCancelAccount.TID
# ///用户标识
l_dict["UserID"] = pCancelAccount.UserID.decode(encoding="gb18030", errors="ignore")
# ///错误代码
l_dict["ErrorID"] = pCancelAccount.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pCancelAccount.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pCancelAccount.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnChangeAccountByBank(self, pChangeAccount):
'''
///银行发起变更银行账号通知
'''
self.PTP_Algos.DumpRspDict("T_ChangeAccount",pChangeAccount)
l_dict={}
"""CThostFtdcChangeAccountField
# ///业务功能码
l_dict["TradeCode"] = pChangeAccount.TradeCode.decode(encoding="gb18030", errors="ignore")
# ///银行代码
l_dict["BankID"] = pChangeAccount.BankID.decode(encoding="gb18030", errors="ignore")
# ///银行分支机构代码
l_dict["BankBranchID"] = pChangeAccount.BankBranchID.decode(encoding="gb18030", errors="ignore")
# ///期商代码
l_dict["BrokerID"] = pChangeAccount.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///期商分支机构代码
l_dict["BrokerBranchID"] = pChangeAccount.BrokerBranchID.decode(encoding="gb18030", errors="ignore")
# ///交易日期
l_dict["TradeDate"] = pChangeAccount.TradeDate.decode(encoding="gb18030", errors="ignore")
# ///交易时间
l_dict["TradeTime"] = pChangeAccount.TradeTime.decode(encoding="gb18030", errors="ignore")
# ///银行流水号
l_dict["BankSerial"] = pChangeAccount.BankSerial.decode(encoding="gb18030", errors="ignore")
# ///交易系统日期
l_dict["TradingDay"] = pChangeAccount.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///银期平台消息流水号
l_dict["PlateSerial"] = pChangeAccount.PlateSerial
# ///最后分片标志
l_dict["LastFragment"] = pChangeAccount.LastFragment.decode(encoding="gb18030", errors="ignore")
# ///会话号
l_dict["SessionID"] = pChangeAccount.SessionID
# ///客户姓名
l_dict["CustomerName"] = pChangeAccount.CustomerName.decode(encoding="gb18030", errors="ignore")
# ///证件类型
l_dict["IdCardType"] = pChangeAccount.IdCardType.decode(encoding="gb18030", errors="ignore")
# ///证件号码
l_dict["IdentifiedCardNo"] = pChangeAccount.IdentifiedCardNo.decode(encoding="gb18030", errors="ignore")
# ///性别
l_dict["Gender"] = pChangeAccount.Gender.decode(encoding="gb18030", errors="ignore")
# ///国家代码
l_dict["CountryCode"] = pChangeAccount.CountryCode.decode(encoding="gb18030", errors="ignore")
# ///客户类型
l_dict["CustType"] = pChangeAccount.CustType.decode(encoding="gb18030", errors="ignore")
# ///地址
l_dict["Address"] = pChangeAccount.Address.decode(encoding="gb18030", errors="ignore")
# ///邮编
l_dict["ZipCode"] = pChangeAccount.ZipCode.decode(encoding="gb18030", errors="ignore")
# ///电话号码
l_dict["Telephone"] = pChangeAccount.Telephone.decode(encoding="gb18030", errors="ignore")
# ///手机
l_dict["MobilePhone"] = pChangeAccount.MobilePhone.decode(encoding="gb18030", errors="ignore")
# ///传真
l_dict["Fax"] = pChangeAccount.Fax.decode(encoding="gb18030", errors="ignore")
# ///电子邮件
l_dict["EMail"] = pChangeAccount.EMail.decode(encoding="gb18030", errors="ignore")
# ///资金账户状态
l_dict["MoneyAccountStatus"] = pChangeAccount.MoneyAccountStatus.decode(encoding="gb18030", errors="ignore")
# ///银行帐号
l_dict["BankAccount"] = pChangeAccount.BankAccount.decode(encoding="gb18030", errors="ignore")
# ///银行密码
l_dict["BankPassWord"] = pChangeAccount.BankPassWord.decode(encoding="gb18030", errors="ignore")
# ///新银行帐号
l_dict["NewBankAccount"] = pChangeAccount.NewBankAccount.decode(encoding="gb18030", errors="ignore")
# ///新银行密码
l_dict["NewBankPassWord"] = pChangeAccount.NewBankPassWord.decode(encoding="gb18030", errors="ignore")
# ///投资者帐号
l_dict["AccountID"] = pChangeAccount.AccountID.decode(encoding="gb18030", errors="ignore")
# ///期货密码
l_dict["Password"] = pChangeAccount.Password.decode(encoding="gb18030", errors="ignore")
# ///银行帐号类型
l_dict["BankAccType"] = pChangeAccount.BankAccType.decode(encoding="gb18030", errors="ignore")
# ///安装编号
l_dict["InstallID"] = pChangeAccount.InstallID
# ///验证客户证件号码标志
l_dict["VerifyCertNoFlag"] = pChangeAccount.VerifyCertNoFlag.decode(encoding="gb18030", errors="ignore")
# ///币种代码
l_dict["CurrencyID"] = pChangeAccount.CurrencyID.decode(encoding="gb18030", errors="ignore")
# ///期货公司银行编码
l_dict["BrokerIDByBank"] = pChangeAccount.BrokerIDByBank.decode(encoding="gb18030", errors="ignore")
# ///银行密码标志
l_dict["BankPwdFlag"] = pChangeAccount.BankPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///期货资金密码核对标志
l_dict["SecuPwdFlag"] = pChangeAccount.SecuPwdFlag.decode(encoding="gb18030", errors="ignore")
# ///交易ID
l_dict["TID"] = pChangeAccount.TID
# ///摘要
l_dict["Digest"] = pChangeAccount.Digest.decode(encoding="gb18030", errors="ignore")
# ///错误代码
l_dict["ErrorID"] = pChangeAccount.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pChangeAccount.ErrorMsg.decode(encoding="gb18030", errors="ignore")
# ///长客户姓名
l_dict["LongCustomerName"] = pChangeAccount.LongCustomerName.decode(encoding="gb18030", errors="ignore")
#"""
# 以下是简单的接口组合案例
def get_Position(self, instrumentID):
return self.PTP_Algos.get_Position(instrumentID)
def get_InstrumentAttr(self, instrumentID):
return self.PTP_Algos.get_InstrumentAttr(instrumentID)
def get_ReqOrderList(self, instrumentID):
return self.PTP_Algos.get_ReqOrderList(instrumentID)
def get_Order_list(self, instrumentID):
return self.PTP_Algos.get_Order_list(instrumentID)
def get_exchangeID_of_instrument(self, instrument_id):
l_ExchageID = ""
try:
#if not isinstance(trader, py_CtpTrader) or not isinstance(instrument_id, str) or len(instrument_id) == 0:
if not isinstance(instrument_id, str) or len(instrument_id) == 0:
return l_ExchageID
l_instrument_Attr_dict = self.get_InstrumentAttr(instrument_id)
if l_instrument_Attr_dict is None:
return l_ExchageID
l_ExchageID = l_instrument_Attr_dict["ExchangeID"]
except Exception as err:
myEnv.logger.error("get_exchangeID_of_instrument failed", exc_info=True)
l_ExchageID = ""
return l_ExchageID
def ai_buy_open(self, investor_id, instrument_id, order_price, order_vol, last_price=0, exchange_ID=""):
l_retVal = -1
try:
l_ExchageID = exchange_ID
if l_ExchageID is None or len(l_ExchageID) == 0:
l_ExchageID = self.get_exchangeID_of_instrument( instrument_id)
pBuyOpen = py_ApiStructure.InputOrderField(
BrokerID=self.broker_id,
InvestorID=investor_id,
ExchangeID=l_ExchageID,
InstrumentID=instrument_id,
UserID=investor_id,
OrderPriceType="2",
Direction="0",
CombOffsetFlag="0", # ///开仓
CombHedgeFlag="1",
LimitPrice=order_price,
VolumeTotalOriginal=order_vol,
TimeCondition="3",
VolumeCondition="1",
MinVolume=1,
ContingentCondition="1",
StopPrice=0,
ForceCloseReason="0",
IsAutoSuspend=0
)
l_retVal = self.ReqOrderInsert(pBuyOpen, "ai_buy_open", last_price)
self.PTP_Algos.restOrderFactor(instrument_id)
l_order_list = self.get_Order_list(instrument_id)
if not l_order_list is None:
for it_Order in l_order_list:
# 如果有反方向报单
# (1)撤掉卖及高价的买
if (it_Order["CombOffsetFlag"] == "0") and ((it_Order["Direction"] == "1") or (
it_Order["Direction"] == "0" and it_Order["LimitPrice"] < order_price)):
l_OrderSysID = it_Order["OrderSysID"]
pOrderAction = py_ApiStructure.InputOrderActionField(
BrokerID=self.broker_id,
InvestorID=investor_id,
UserID=investor_id,
ExchangeID=l_ExchageID,
ActionFlag="0", # ///删除报单
OrderSysID=l_OrderSysID,
InstrumentID=instrument_id
)
self.ReqOrderAction(pOrderAction)
l_retVal = 0
return l_retVal
except Exception as err:
myEnv.logger.error("ai_buy_open", exc_info=True)
return l_retVal
def ai_sell_open(self, investor_id, instrument_id, order_price, order_vol, last_price=0,
exchange_ID=""):
l_retVal = -1
try:
l_ExchageID = exchange_ID
if l_ExchageID is None or len(l_ExchageID) == 0:
l_ExchageID = self.get_exchangeID_of_instrument( instrument_id)
pSellOpen = py_ApiStructure.InputOrderField(
BrokerID=self.broker_id,
InvestorID=investor_id,
ExchangeID=l_ExchageID,
InstrumentID=instrument_id,
UserID=investor_id,
OrderPriceType="2",
Direction="1",
CombOffsetFlag="0", # ///开仓
CombHedgeFlag="1",
LimitPrice=order_price,
VolumeTotalOriginal=order_vol,
TimeCondition="3",
VolumeCondition="1",
MinVolume=1,
ContingentCondition="1",
StopPrice=0,
ForceCloseReason="0",
IsAutoSuspend=0
)
l_retVal = self.ReqOrderInsert(pSellOpen, "ai_sell_open", last_price)
self.PTP_Algos.restOrderFactor(instrument_id)
l_order_list = self.get_Order_list(instrument_id)
if not l_order_list is None:
for it_Order in l_order_list:
# 如果有反方向报单
# (1)撤掉买及低价的卖
# 如果有买方向报单
if (it_Order["CombOffsetFlag"] == "0") and ((it_Order["Direction"] == "0") or (
it_Order["Direction"] == "1" and it_Order["LimitPrice"] > order_price)):
l_OrderSysID = it_Order["OrderSysID"]
pOrderAction = py_ApiStructure.InputOrderActionField(
BrokerID=self.broker_id,
InvestorID=investor_id,
UserID=investor_id,
ExchangeID=l_ExchageID,
ActionFlag="0", # ///删除报单
OrderSysID=l_OrderSysID,
InstrumentID=instrument_id
)
self.ReqOrderAction(pOrderAction)
return l_retVal
except Exception as err:
myEnv.logger.error("ai_sell_open", exc_info=True)
def withdraw_buy(self, investor_id, instrument_id, exchange_ID=""):
l_retVal = -1
try:
l_ExchageID = exchange_ID
if l_ExchageID is None or len(l_ExchageID) == 0:
l_ExchageID = self.get_exchangeID_of_instrument( instrument_id)
l_order_list = self.get_Order_list(instrument_id)
if not l_order_list is None:
for it_Order in l_order_list:
# (1)撤掉买
if it_Order["Direction"] == "0" and it_Order["OrderStatus"] not in ["0", "5", "a"]:
l_OrderSysID = it_Order["OrderSysID"]
pOrderAction = py_ApiStructure.InputOrderActionField(
BrokerID=self.broker_id,
InvestorID=investor_id,
UserID=investor_id,
ExchangeID=l_ExchageID,
ActionFlag="0", # ///删除报单
OrderSysID=l_OrderSysID,
InstrumentID=instrument_id
)
self.ReqOrderAction(pOrderAction)
l_retVal = 0
return l_retVal
except Exception as err:
myEnv.logger.error("withdraw_buy", exc_info=True)
return l_retVal
def withdraw_sell(self, investor_id, instrument_id, exchange_ID=""):
l_retVal = -1
try:
l_ExchageID = exchange_ID
if l_ExchageID is None or len(l_ExchageID) == 0:
l_ExchageID = self.get_exchangeID_of_instrument( instrument_id)
l_order_list = self.get_Order_list(instrument_id)
if not l_order_list is None:
for it_Order in l_order_list:
# (1)撤掉买
if it_Order["Direction"] == "1" and it_Order["OrderStatus"] not in ["0", "5", "a"]:
l_OrderSysID = it_Order["OrderSysID"]
pOrderAction = py_ApiStructure.InputOrderActionField(
BrokerID=self.broker_id,
InvestorID=investor_id,
UserID=investor_id,
ExchangeID=l_ExchageID,
ActionFlag="0", # ///删除报单
OrderSysID=l_OrderSysID,
InstrumentID=instrument_id
)
self.ReqOrderAction(pOrderAction)
l_retVal = 0
return l_retVal
except Exception as err:
myEnv.logger.error("withdraw_sell", exc_info=True)
return l_retVal
def buy_open(self, investor_id, instrument_id, order_price, order_vol, last_price=0, exchange_ID=""):
l_retVal = -1
try:
l_ExchageID = exchange_ID
if l_ExchageID is None or len(l_ExchageID) == 0:
l_ExchageID = self.get_exchangeID_of_instrument( instrument_id)
pBuyOpen = py_ApiStructure.InputOrderField(
BrokerID=self.broker_id,
InvestorID=investor_id,
ExchangeID=l_ExchageID,
InstrumentID=instrument_id,
UserID=investor_id,
OrderPriceType="2",
Direction="0",
CombOffsetFlag="0", # ///开仓
CombHedgeFlag="1",
LimitPrice=order_price,
VolumeTotalOriginal=order_vol,
TimeCondition="3",
VolumeCondition="1",
MinVolume=1,
ContingentCondition="1",
StopPrice=0,
ForceCloseReason="0",
IsAutoSuspend=0
)
l_retVal = self.ReqOrderInsert(pBuyOpen, "buy_open", last_price)
self.PTP_Algos.restOrderFactor(instrument_id)
except Exception as err:
myEnv.logger.error("buy_open", exc_info=True)
l_retVal = -1
return l_retVal
def sell_open(self, investor_id, instrument_id, order_price, order_vol, last_price=0,
exchange_ID=""):
l_retVal = -1
try:
l_ExchageID = exchange_ID
if l_ExchageID is None or len(l_ExchageID) == 0:
l_ExchageID = self.get_exchangeID_of_instrument( instrument_id)
pSellOpen = py_ApiStructure.InputOrderField(
BrokerID=self.broker_id,
InvestorID=investor_id,
ExchangeID=l_ExchageID,
InstrumentID=instrument_id,
UserID=investor_id,
OrderPriceType="2",
Direction="1",
CombOffsetFlag="0", # ///开仓
CombHedgeFlag="1",
LimitPrice=order_price,
VolumeTotalOriginal=order_vol,
TimeCondition="3",
VolumeCondition="1",
MinVolume=1,
ContingentCondition="1",
StopPrice=0,
ForceCloseReason="0",
IsAutoSuspend=0
)
l_retVal = self.ReqOrderInsert(pSellOpen, "sell_open", last_price)
self.PTP_Algos.restOrderFactor(instrument_id)
except Exception as err:
myEnv.logger.error("sell_open", exc_info=True)
l_retVal = -1
return l_retVal
def buy_close(self, investor_id, instrument_id, order_price, order_vol, last_price=0,
exchange_ID=""):
l_retVal = -1
try:
l_ExchageID = exchange_ID
if l_ExchageID is None or len(l_ExchageID) == 0:
l_ExchageID = self.get_exchangeID_of_instrument( instrument_id)
# 获取仓位
l_position_list = self.get_Position(instrument_id)
l_remain = order_vol
if not l_position_list is None:
for it_pos in l_position_list:
if it_pos["PosiDirection"] == "3" and it_pos["Position"] > 0 and l_remain > 0: # ///空头
l_close_vol = 1
if l_ExchageID == "SHFE":
if it_pos["TodayPosition"] > 0:
l_CombOffsetFlag = "3" # 平今
l_close_vol = min(it_pos["TodayPosition"], l_remain)
else:
l_CombOffsetFlag = "4" # 平昨
l_close_vol = min(it_pos["YdPosition"], l_remain)
else:
l_CombOffsetFlag = "1" # 平仓
l_close_vol = min(it_pos["Position"], l_remain)
# 改进,撤掉以前价格不合理的平仓
# 报买平单
pBuyClose = py_ApiStructure.InputOrderField(
BrokerID=self.broker_id,
InvestorID=investor_id,
ExchangeID=l_ExchageID,
InstrumentID=instrument_id,
UserID=investor_id,
OrderPriceType="2",
Direction="0",
CombOffsetFlag=l_CombOffsetFlag,
CombHedgeFlag="1",
LimitPrice=order_price, # 可以考虑减少一个tick确保能卖掉
VolumeTotalOriginal=l_close_vol,
TimeCondition="3",
VolumeCondition="1",
MinVolume=1,
ContingentCondition="1",
StopPrice=0,
ForceCloseReason="0",
IsAutoSuspend=0
)
l_retVal = self.ReqOrderInsert(pBuyClose, "buy_close", last_price)
self.PTP_Algos.restOrderFactor(instrument_id)
l_remain = l_remain - l_close_vol
except Exception as err:
myEnv.logger.error("buy_close", exc_info=True)
def sell_close(self, investor_id, instrument_id, order_price, order_vol, last_price=0,
exchange_ID=""):
l_retVal = -1
try:
l_ExchageID = exchange_ID
if l_ExchageID is None or len(l_ExchageID) == 0:
l_ExchageID = self.get_exchangeID_of_instrument( instrument_id)
# 获取仓位
l_position_list = self.get_Position(instrument_id)
l_remain = order_vol
# TThostFtdcVolumeType YdPosition; ///上日持仓
# TThostFtdcVolumeType Position; ///今日总持仓
# TThostFtdcVolumeType TodayPosition; ///今日持仓
if not l_position_list is None:
for it_pos in l_position_list:
if it_pos["PosiDirection"] == "2" and it_pos["Position"] > 0 and l_remain > 0: # ///多头
l_close_vol = 1
if l_ExchageID == "SHFE":
if it_pos["TodayPosition"] > 0:
l_CombOffsetFlag = "3" # 平今
l_close_vol = min(it_pos["TodayPosition"], l_remain)
else:
l_CombOffsetFlag = "4" # 平昨
l_close_vol = min(it_pos["YdPosition"], l_remain)
else:
l_CombOffsetFlag = "1" # 平仓
l_close_vol = min(it_pos["Position"], l_remain)
# 改进,撤掉以前价格不合理的平仓,
# 报卖平单
pSellClose = py_ApiStructure.InputOrderField(
BrokerID=self.broker_id,
InvestorID=investor_id,
ExchangeID=l_ExchageID,
InstrumentID=instrument_id,
UserID=investor_id,
OrderPriceType="2",
Direction="1",
CombOffsetFlag=l_CombOffsetFlag,
CombHedgeFlag="1",
LimitPrice=order_price, # 可以考虑减少一个tick确保能卖掉
VolumeTotalOriginal=l_close_vol,
TimeCondition="3",
VolumeCondition="1",
MinVolume=1,
ContingentCondition="1",
StopPrice=0,
ForceCloseReason="0",
IsAutoSuspend=0
)
l_retVal = self.ReqOrderInsert(pSellClose, "sell_close", last_price)
self.PTP_Algos.restOrderFactor(instrument_id)
l_remain = l_remain - l_close_vol
except Exception as err:
myEnv.logger.error("sell_close", exc_info=True) | ytp1 | /ytp1-6.3.12-cp36-cp36m-win_amd64.whl/ptp/py_CtpTrader.py | py_CtpTrader.py |
import cProfile
import pstats
import io
import os
import time,datetime
import configparser
import sys
from ptp import py_ApiStructure
from ptp import py_base
from ptp import CythonLib
from ptp.CythonLib import printString
from ptp.CythonLib import printNumber
import cfg.ptp_env as myEnv
import cfg.ptp_can_change_env as myDEnv #需要动态实时变化的
from ptp.MdApi import MdApiWrapper
class py_CtpMd(MdApiWrapper):
def __init__(self, server
, broker_id, investor_id, password
, i_queue_list=[]
, pszFlowPath="", bIsUsingUdp=False, bIsMulticast=False):
try:
#Profiler
if myEnv.Profiler == 1:
self.Profiler = cProfile.Profile()
self.Profiler.enable()
str_date_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y%m%d_%H%M%S")
self.pid_file = "log/PID_MD.%s.%s.log"%(os.getpid(),str_date_time)
l_pid_file = open(self.pid_file, "w", encoding="utf-8")
l_pid_file.write(str(os.getpid()))
l_pid_file.close()
#调用情况
self.m_started = 0
self.req_call = {}
#基本信息
self.broker_id = broker_id
self.investor_id = investor_id
self.password = password
self.md_servers = server
self.pszFlowPath = pszFlowPath
self.bIsUsingUdp = bIsUsingUdp
self.bIsMulticast= bIsMulticast
#进程间通信
self.m_md_queue_list = i_queue_list
self.m_md_sum = 0
#Algos
self.PTP_Algos = CythonLib.CPTPAlgos()
#基础配置
self.config = configparser.ConfigParser()
self.config.read("cfg/ptp.ini",encoding="utf-8")
#0:实盘行情 1:行情回测
self.Md_Rule = int(self.config.get("TRADE_MODE", "Md_Rule"))
self.Md_Gap = float(self.config.get("TRADE_MODE", "Md_Gap"))
self.Md_Trading_Day = self.config.get("TRADE_MODE", "Md_Trading_Day")
nRetVal = self.Init_Base()
if nRetVal != 0:
myEnv.logger.error("py_CtpMd Init_Base failed.")
sys.exit(1)
if self.Md_Rule == 0:
l_found=0
for the_server in server:
info_list = the_server.split(":")
ip = info_list[1][2:]
port = int(info_list[2])
if not py_base.check_service(ip,port):
print(the_server + " is closed")
else:
print(the_server + " is OK!")
l_found=1
if l_found == 0:
print("There is no active MD server")
sys.exit(1)
#初始化运行环境,只有调用后,接口才开始发起前置的连接请求。
super(py_CtpMd, self).Init_Net()
self.SubscribeMarketData(myDEnv.my_instrument_id)
#启动完成
self.m_started = 1
myEnv.logger.info("行情启动完毕(broker_id:%s,investor_id:%s,server:%s)"%(broker_id,investor_id,server))
except Exception as err:
myEnv.logger.error("py_CtpMd init failed.", exc_info=True)
def __del__(self):
if myEnv.Profiler == 1:
self.Profiler.disable()
s = io.StringIO()
ps = pstats.Stats(self.Profiler, stream=s).sort_stats("cumulative")
ps.print_stats()
pr_file = open("log/Profiler_MD.%s.log"%os.getpid(), "w", encoding="utf-8")
pr_file.write(s.getvalue())
pr_file.close()
if os.path.exists(self.pid_file):
os.remove(self.pid_file)
"""
当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。
#OnFrontConnected初始化成功后会被回调
#这时这里自动登录
"""
def OnFrontConnected(self):
self.__Connected = 1
user_login = py_ApiStructure.ReqUserLoginField(BrokerID=self.broker_id,
UserID=self.investor_id,
Password=self.password
)
self.ReqUserLogin(user_login)
def OnRspUserLogin(self, pRspUserLogin, pRspInfo, nRequestID, bIsLast):
#交易日
l_TradingDay=pRspUserLogin.TradingDay.decode(encoding="gb18030", errors="ignore")
#登录成功时间
l_LoginTime=pRspUserLogin.LoginTime.decode(encoding="gb18030", errors="ignore")
#经纪公司代码
l_BrokerID=pRspUserLogin.BrokerID.decode(encoding="gb18030", errors="ignore")
#用户代码
l_UserID=pRspUserLogin.UserID.decode(encoding="gb18030", errors="ignore")
#交易系统名称
l_SystemName=pRspUserLogin.SystemName.decode(encoding="gb18030", errors="ignore")
#前置编号
l_FrontID=pRspUserLogin.FrontID
#会话编号
l_SessionID=pRspUserLogin.SessionID
#最大报单引用
l_MaxOrderRef=pRspUserLogin.MaxOrderRef.decode(encoding="gb18030", errors="ignore")
#上期所时间
l_SHFETime=pRspUserLogin.SHFETime.decode(encoding="gb18030", errors="ignore")
#大商所时间
l_DCETime=pRspUserLogin.DCETime.decode(encoding="gb18030", errors="ignore")
#郑商所时间
l_CZCETime=pRspUserLogin.CZCETime.decode(encoding="gb18030", errors="ignore")
#中金所时间
l_FFEXTime=pRspUserLogin.FFEXTime.decode(encoding="gb18030", errors="ignore")
#能源中心时间
l_INETime=pRspUserLogin.INETime.decode(encoding="gb18030", errors="ignore")
#错误代码
l_ErrorID=pRspInfo.ErrorID
if l_ErrorID == 0:
self.Logined = 1
#错误信息
l_ErrorMsg=pRspInfo.ErrorMsg.decode(encoding="gb18030", errors="ignore")
#申请编号
l_nRequestID = nRequestID
#是否为最后一个包
l_bIsLast = bIsLast
def Join(self) -> int:
"""
等待接口线程结束运行
@return 线程退出代码
:return:
"""
return super(py_CtpMd, self).Join()
def GetTradingDay(self) -> str:
"""
获取当前交易日
@retrun 获取到的交易日
@remark 只有登录成功后,才能得到正确的交易日
:return:
"""
day = super(py_CtpMd, self).GetTradingDay()
return day.decode(encoding="gb18030", errors="ignore")
def RegisterNameServer(self, pszNsAddress: str):
"""
注册名字服务器网络地址
@param pszNsAddress:名字服务器网络地址。
@remark 网络地址的格式为:“protocol:# ipaddress:port”,如:”tcp:# 127.0.0.1:12001”。
@remark “tcp”代表传输协议,“127.0.0.1”代表服务器地址。”12001”代表服务器端口号。
设置名字服务器网络地址。RegisterNameServer 优先于 RegisterFront 。
调用前需要先使用 RegisterFensUserInfo 设置登录模式。
"""
super(py_CtpMd, self).RegisterNameServer(pszNsAddress.encode())
def RegisterFensUserInfo(self, pFensUserInfo):
"""
注册名字服务器用户信息
@param pFensUserInfo:用户信息。
"""
super(py_CtpMd, self).RegisterFensUserInfo(pFensUserInfo)
def SubscribeMarketData(self, pInstrumentID: list) -> int:
"""
订阅行情。
char *ppInstrumentID[]
订阅行情,对应响应 OnRspSubMarketData;订阅成功后,推送OnRtnDepthMarketData
0,代表成功。
-1,表示网络连接失败;
-2,表示未处理请求超过许可数;
-3,表示每秒发送请求数超过许可数。
"""
ids = [bytes(item, encoding="utf-8") for item in pInstrumentID]
return super(py_CtpMd, self).SubscribeMarketData(ids)
def UnSubscribeMarketData(self, pInstrumentID: list) -> int:
"""
退订行情。
@param ppInstrumentID 合约ID
:return: int
"""
ids = [bytes(item, encoding="utf-8") for item in pInstrumentID]
return super(py_CtpMd, self).UnSubscribeMarketData(ids)
def SubscribeForQuoteRsp(self, pInstrumentID: list) -> int:
"""
订阅询价。
订阅询价,对应响应OnRspSubForQuoteRsp;订阅成功后推送OnRtnForQuoteRsp。
"""
ids = [bytes(item, encoding="utf-8") for item in pInstrumentID]
return super(py_CtpMd, self).SubscribeForQuoteRsp(ids)
def UnSubscribeForQuoteRsp(self, pInstrumentID: list) -> int:
"""
退订询价。
:param pInstrumentID: 合约ID list
:return: int
"""
ids = [bytes(item, encoding="utf-8") for item in pInstrumentID]
return super(py_CtpMd, self).UnSubscribeForQuoteRsp(ids)
"""
当客户端与交易后台通信连接断开时,该方法被调用。当发生这个情况后,API会自动重新连接,客户端可不做处理。
@param nReason 错误原因
0x1001 网络读失败
0x1002 网络写失败
0x2001 接收心跳超时
0x2002 发送心跳失败
0x2003 收到错误报文
"""
def OnFrontDisconnected(self, nReason):
print(nReason)
"""
心跳超时警告。当长时间未收到报文时,该方法被调用。
@param nTimeLapse 距离上次接收报文的时间
"""
def OnHeartBeatWarning(self, nTimeLapse):
print(nTimeLapse)
def ReqUserLogin(self, pReqUserLogin):
'''
///用户登录请求
'''
"""CThostFtdcReqUserLoginField
l_CThostFtdcReqUserLoginField=py_ApiStructure.ReqUserLoginField(
TradingDay ='?' # ///交易日
,BrokerID ='?' # ///经纪公司代码
,UserID ='?' # ///用户代码
,Password ='?' # ///密码
,UserProductInfo ='?' # ///用户端产品信息
,InterfaceProductInfo ='?' # ///接口端产品信息
,ProtocolInfo ='?' # ///协议信息
,MacAddress ='?' # ///Mac地址
,OneTimePassword ='?' # ///动态密码
,ClientIPAddress ='?' # ///终端IP地址
,LoginRemark ='?' # ///登录备注
)
#"""
self.req_call['UserLogin'] = 0
if self.Md_Rule == 0:
return super(py_CtpMd, self).ReqUserLogin(pReqUserLogin,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqUserLogin(pReqUserLogin,self.Inc_RequestID() )
def ReqUserLogout(self, pUserLogout):
'''
///登出请求
'''
"""CThostFtdcUserLogoutField
l_CThostFtdcUserLogoutField=py_ApiStructure.UserLogoutField(
BrokerID ='?' # ///经纪公司代码
,UserID ='?' # ///用户代码
)
#"""
self.req_call['UserLogout'] = 0
if self.Md_Rule == 0:
return super(py_CtpMd, self).ReqUserLogout(pUserLogout,self.Inc_RequestID() )
else:
return self.PTP_Algos.ReqUserLogout(pUserLogout,self.Inc_RequestID() )
def OnRspUserLogout(self, pUserLogout, pRspInfo, nRequestID, bIsLast):
'''
///登出请求响应
'''
if bIsLast == True:
self.req_call['UserLogout'] = 1
self.PTP_Algos.DumpRspDict("T_UserLogout",pUserLogout)
l_dict={}
"""CThostFtdcUserLogoutField
# ///经纪公司代码
l_dict["BrokerID"] = pUserLogout.BrokerID.decode(encoding="gb18030", errors="ignore")
# ///用户代码
l_dict["UserID"] = pUserLogout.UserID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspError(self, pRspInfo, nRequestID, bIsLast):
'''
///错误应答
'''
if bIsLast == True:
self.req_call['Error'] = 1
self.PTP_Algos.DumpRspDict("T_RspInfo",pRspInfo)
l_dict={}
"""CThostFtdcRspInfoField
# ///错误代码
l_dict["ErrorID"] = pRspInfo.ErrorID
# ///错误信息
l_dict["ErrorMsg"] = pRspInfo.ErrorMsg.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspSubMarketData(self, pSpecificInstrument, pRspInfo, nRequestID, bIsLast):
'''
///订阅行情应答
'''
if bIsLast == True:
self.req_call['SubMarketData'] = 1
self.PTP_Algos.DumpRspDict("T_SpecificInstrument",pSpecificInstrument)
l_dict={}
"""CThostFtdcSpecificInstrumentField
# ///合约代码
l_dict["InstrumentID"] = pSpecificInstrument.InstrumentID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspUnSubMarketData(self, pSpecificInstrument, pRspInfo, nRequestID, bIsLast):
'''
///取消订阅行情应答
'''
if bIsLast == True:
self.req_call['UnSubMarketData'] = 1
self.PTP_Algos.DumpRspDict("T_SpecificInstrument",pSpecificInstrument)
l_dict={}
"""CThostFtdcSpecificInstrumentField
# ///合约代码
l_dict["InstrumentID"] = pSpecificInstrument.InstrumentID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspSubForQuoteRsp(self, pSpecificInstrument, pRspInfo, nRequestID, bIsLast):
'''
///订阅询价应答
'''
if bIsLast == True:
self.req_call['SubForQuoteRsp'] = 1
self.PTP_Algos.DumpRspDict("T_SpecificInstrument",pSpecificInstrument)
l_dict={}
"""CThostFtdcSpecificInstrumentField
# ///合约代码
l_dict["InstrumentID"] = pSpecificInstrument.InstrumentID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRspUnSubForQuoteRsp(self, pSpecificInstrument, pRspInfo, nRequestID, bIsLast):
'''
///取消订阅询价应答
'''
if bIsLast == True:
self.req_call['UnSubForQuoteRsp'] = 1
self.PTP_Algos.DumpRspDict("T_SpecificInstrument",pSpecificInstrument)
l_dict={}
"""CThostFtdcSpecificInstrumentField
# ///合约代码
l_dict["InstrumentID"] = pSpecificInstrument.InstrumentID.decode(encoding="gb18030", errors="ignore")
#"""
def OnRtnDepthMarketData(self, pDepthMarketData):
'''
///深度行情通知
'''
self.PTP_Algos.DumpRspDict("T_DepthMarketData",pDepthMarketData)
l_dict={}
#"""CThostFtdcDepthMarketDataField
# ///交易日
l_dict["TradingDay"] = pDepthMarketData.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pDepthMarketData.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pDepthMarketData.ExchangeID.decode(encoding="gb18030", errors="ignore")
# ///合约在交易所的代码
l_dict["ExchangeInstID"] = pDepthMarketData.ExchangeInstID.decode(encoding="gb18030", errors="ignore")
# ///最新价
l_dict["LastPrice"] = pDepthMarketData.LastPrice
# ///上次结算价
l_dict["PreSettlementPrice"] = pDepthMarketData.PreSettlementPrice
# ///昨收盘
l_dict["PreClosePrice"] = pDepthMarketData.PreClosePrice
# ///昨持仓量
l_dict["PreOpenInterest"] = pDepthMarketData.PreOpenInterest
# ///今开盘
l_dict["OpenPrice"] = pDepthMarketData.OpenPrice
# ///最高价
l_dict["HighestPrice"] = pDepthMarketData.HighestPrice
# ///最低价
l_dict["LowestPrice"] = pDepthMarketData.LowestPrice
# ///数量
l_dict["Volume"] = pDepthMarketData.Volume
# ///成交金额
l_dict["Turnover"] = pDepthMarketData.Turnover
# ///持仓量
l_dict["OpenInterest"] = pDepthMarketData.OpenInterest
# ///今收盘
l_dict["ClosePrice"] = pDepthMarketData.ClosePrice
# ///本次结算价
l_dict["SettlementPrice"] = pDepthMarketData.SettlementPrice
# ///涨停板价
l_dict["UpperLimitPrice"] = pDepthMarketData.UpperLimitPrice
# ///跌停板价
l_dict["LowerLimitPrice"] = pDepthMarketData.LowerLimitPrice
# ///昨虚实度
l_dict["PreDelta"] = pDepthMarketData.PreDelta
# ///今虚实度
l_dict["CurrDelta"] = pDepthMarketData.CurrDelta
# ///最后修改时间
l_dict["UpdateTime"] = pDepthMarketData.UpdateTime.decode(encoding="gb18030", errors="ignore")
# ///最后修改毫秒
l_dict["UpdateMillisec"] = pDepthMarketData.UpdateMillisec
# ///申买价一
l_dict["BidPrice1"] = pDepthMarketData.BidPrice1
# ///申买量一
l_dict["BidVolume1"] = pDepthMarketData.BidVolume1
# ///申卖价一
l_dict["AskPrice1"] = pDepthMarketData.AskPrice1
# ///申卖量一
l_dict["AskVolume1"] = pDepthMarketData.AskVolume1
# ///申买价二
l_dict["BidPrice2"] = pDepthMarketData.BidPrice2
# ///申买量二
l_dict["BidVolume2"] = pDepthMarketData.BidVolume2
# ///申卖价二
l_dict["AskPrice2"] = pDepthMarketData.AskPrice2
# ///申卖量二
l_dict["AskVolume2"] = pDepthMarketData.AskVolume2
# ///申买价三
l_dict["BidPrice3"] = pDepthMarketData.BidPrice3
# ///申买量三
l_dict["BidVolume3"] = pDepthMarketData.BidVolume3
# ///申卖价三
l_dict["AskPrice3"] = pDepthMarketData.AskPrice3
# ///申卖量三
l_dict["AskVolume3"] = pDepthMarketData.AskVolume3
# ///申买价四
l_dict["BidPrice4"] = pDepthMarketData.BidPrice4
# ///申买量四
l_dict["BidVolume4"] = pDepthMarketData.BidVolume4
# ///申卖价四
l_dict["AskPrice4"] = pDepthMarketData.AskPrice4
# ///申卖量四
l_dict["AskVolume4"] = pDepthMarketData.AskVolume4
# ///申买价五
l_dict["BidPrice5"] = pDepthMarketData.BidPrice5
# ///申买量五
l_dict["BidVolume5"] = pDepthMarketData.BidVolume5
# ///申卖价五
l_dict["AskPrice5"] = pDepthMarketData.AskPrice5
# ///申卖量五
l_dict["AskVolume5"] = pDepthMarketData.AskVolume5
# ///当日均价
l_dict["AveragePrice"] = pDepthMarketData.AveragePrice
# ///业务日期
l_dict["ActionDay"] = pDepthMarketData.ActionDay.decode(encoding="gb18030", errors="ignore")
#"""
for md_queue in self.m_md_queue_list:
md_queue.put(l_dict)
self.m_md_sum = self.m_md_sum + 1
def OnRtnForQuoteRsp(self, pForQuoteRsp):
'''
///询价通知
'''
self.PTP_Algos.DumpRspDict("T_ForQuoteRsp",pForQuoteRsp)
l_dict={}
"""CThostFtdcForQuoteRspField
# ///交易日
l_dict["TradingDay"] = pForQuoteRsp.TradingDay.decode(encoding="gb18030", errors="ignore")
# ///合约代码
l_dict["InstrumentID"] = pForQuoteRsp.InstrumentID.decode(encoding="gb18030", errors="ignore")
# ///询价编号
l_dict["ForQuoteSysID"] = pForQuoteRsp.ForQuoteSysID.decode(encoding="gb18030", errors="ignore")
# ///询价时间
l_dict["ForQuoteTime"] = pForQuoteRsp.ForQuoteTime.decode(encoding="gb18030", errors="ignore")
# ///业务日期
l_dict["ActionDay"] = pForQuoteRsp.ActionDay.decode(encoding="gb18030", errors="ignore")
# ///交易所代码
l_dict["ExchangeID"] = pForQuoteRsp.ExchangeID.decode(encoding="gb18030", errors="ignore")
#""" | ytp1 | /ytp1-6.3.12-cp36-cp36m-win_amd64.whl/ptp/py_CtpMd.py | py_CtpMd.py |
# ytpodgen - turns YouTube live streams into podcasts
## prerequisite
- python3 and pip
## first time setup
```
python3 -m pip install --user ytpodgen
```
Set environment variable `SLACK_WEBHOOK_URL`, if you want Slack notification.
If you want to upload files to Cloudflare R2 as well, don't forget to set three environment variables for Cloudflare R2.
- R2_ENDPOINT_URL
- R2_ACCESS_KEY_ID
- R2_SECRET_ACCESS_KEY
For now, R2 bucket name must be `podcast`.
## examples
### wait for new livestream, and once on the air, record it and generate podcast RSS in background
```
TITLE=<title> ; #title for your podcast
LIVEURL=<liveurl> ; #YouTube live URL that ends with "/live"
HOSTNAME=<hostname> ; #hostname to serve files from
screen -dmS ${TITLE} ytpodgen --liveurl ${LIVEURL} --title ${TITLE} --hostname ${HOSTNAME}
```
When completed, `ytpodgen` will wait for another livestream. Since all the waiting might take a while, I prefer running this in background using `screen`.
### Why not upload them as well!?
You can pass `--upload-r2` argument to enable file uploadig to Cloudflare R2. By enabling it, mp3s/RSS are uploaded to Cloudflare R2.
For example, by running the commands below , you create a screen session that waits for YouTube livestream on the given URL and saves the data under current directory if there is a livestream.
```
TITLE=<title> ; #title for your podcast
LIVEURL=<liveurl> ; #YouTube live URL that ends with "/live"
HOSTNAME=<hostname> ; #hostname to serve files from
screen -dmS ${TITLE} ytpodgen --upload-r2 --liveurl ${LIVEURL} --title ${TITLE} --hostname ${HOSTNAME}
```
### I just want to generate RSS from mp3 files, no download/upload needed
```
TITLE=<title> ; #title for your podcast
HOSTNAME=<hostname> ; #hostname to serve files from
ytpodgen --title ${TITLE} --hostname ${HOSTNAME}
```
This generates `index.rss` file under current directory and exits.
## Why only Cloudflare R2, and not other S3-compatible cloud storage?
Because:
- It offers free tier for up to 10GB of storage space per month
- With Cloudflare Worker, basic auth can be applied to the uploaded files that are made public
## how I configured basic auth on Cloudflare R2 using Cloudflare Workers
1. connected a custom domain to my R2 bucket, to make the bucket public. [docs](https://developers.cloudflare.com/r2/buckets/public-buckets/)
2. configured a basic auth worker by following steps described [here](https://qiita.com/AnaKutsu/items/1c8bd0eb938edd3c0e0a).
3. replaced the plaintext declaration of password with worker env var. [docs](https://developers.cloudflare.com/workers/platform/environment-variables/#environment-variables-via-the-dashboard)
4. added a trigger(custom domain route) to the basic auth worker. [docs](https://developers.cloudflare.com/workers/platform/triggers/routes/)
## TODO/IDEAS
- [ ] replace Click package with argparse (argparse is lightweight and suits ytpodgen well) ref: [1](https://stackoverflow.com/questions/10974491/how-to-combine-interactive-prompting-with-argparse-in-python)
- [ ] simplify basic auth on R2 bucket e.g. [1](https://zenn.dev/yusukebe/articles/54649c85beef1b) [2](https://zenn.dev/morinokami/articles/url-shortener-with-hono-on-cloudflare-workers)
- [ ] log when download has started
- [x] add an option to specify output path
- [x] use `boto3` for uploading files in order to remove `rclone`
- [x] generate rss feed with python code in order to remove `dropcaster`
- [x] embed `yt-dlp` into ytpodgen, instead of calling it via docker
- [x] use `--live-from-start` option for yt-dlp if the stream has already started
- [x] package this app using `poetry` so that I can install this using `pip`
- [x] introduce [Click](https://click.palletsprojects.com/en/8.0.x/) for this project | ytpodgen | /ytpodgen-0.2.3.tar.gz/ytpodgen-0.2.3/README.md | README.md |
# ytproofreading
A python module to use the proofreading support api of Yahoo! japan
## Requirement
* beautifulsoup4
* certifi
* chardet
* idna
* lxml
* requests
* soupsieve
* urllib3
## Installation
```bash
$ pip install ytproofreading
```
## Usage
```python
import ytproofreading
appid = "Client ID obtained from the Yahoo! japan Developer Network"
kousei = ytproofreading.Kousei(appid)
text = "遙か彼方に小形飛行機が見える。"
print(kousei.proofreading_support(text))
"""
[{'startpos': '0', 'length': '2', 'surface': '遙か', 'shitekiword': '●か', 'shitekiinfo': '表外漢字あり'},
{'startpos': '2', 'length': '2', 'surface': '彼方', 'shitekiword': '彼方(かなた)', 'shitekiinfo': '用字'},
{'startpos': '5', 'length': '5', 'surface': '小形飛行機', 'shitekiword': '小型飛行機', 'shitekiinfo': '誤変換'}]
"""
print(kousei.proofreading_support(text, 1))
"""
[{'startpos': '5', 'length': '5', 'surface': '小形飛行機', 'shitekiword': '小型飛行機', 'shitekiinfo': '誤変換'}]
"""
print(kousei.proofreading_support(text, 0, 1))
"""
[{'startpos': '0', 'length': '2', 'surface': '遙か', 'shitekiword': '●か', 'shitekiinfo': '表外漢字あり'},
{'startpos': '2', 'length': '2', 'surface': '彼方', 'shitekiword': '彼方(かなた)', 'shitekiinfo': '用字'}]
"""
```
## Note
For more information about arguments and errors, please refer to the following URL.
* arguments: https://developer.yahoo.co.jp/webapi/jlp/kousei/v1/kousei.html
* errors: https://developer.yahoo.co.jp/appendix/errors.html
## Author
* 6ast1an979
* email: [email protected]
* twitter: [@6ast1an979](https://twitter.com/6ast1an979)
## License
"ytproofreading" is under [MIT license](https://en.wikipedia.org/wiki/MIT_License).
| ytproofreading | /ytproofreading-1.4.tar.gz/ytproofreading-1.4/README.md | README.md |
# YouTube Terminal Player and Search
YouTube Terminal Player and Search is a simple tools to search [youtube]('https://youtube.com') from the terminal. It also gives you the url, so you can use [mpv]('https://mpv.io') to watch the video.
This bypasses the need to use youtube at all. Also, ytps doesn't use the youtube REST API, it only uses programs that scrape youtube. ytps uses many modules that scrap youtube.
*ytps doesn't on it's own provides no results. It only uses the below modules and compiles them to look beautiful and nice*.
## 3rd party modules used in ytps:
*youtube-search-python*: [website]('https://github.com/alexmercerind/youtube-search-python') ;
*youtube-search*: [website]('https://github.com/joetats/youtube_search') ;
*rich*: [website]('https://github.com/willmcgugan/rich')
## Usage
1. General Usage
```bash
ytps "youtube_search_term"
```
2. Open latest video in mpv
```bash
ytps -o "youtube_search_term"
```
3. Open more relevant but slower results
```bash
ytps -l "youtube_search_term"
```
4. Play Url or Most Relevant Result based on string
```bash
ytps -p "youtube_search_term"
```
5. Channel Info
```bash
ytps -c "channel_name"
```
6. Video Info
```bash
ytps --info "video_url"
```
7. About
```bash
ytps -a "any_string"
```
8. Help
```bash
ytps --help
```
9. Version
```bash
ytps --version
```
## License
### The MIT License (MIT)
Copyright © 2021 NoobScience
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
>[Github](https://newtoallofthis123.github.io/ytps)
>Made By [NoobScience](https://newtoallofthis123.github.io/About) | ytps | /ytps-1.2.2.tar.gz/ytps-1.2.2/README.md | README.md |
# ytpy
[](https://www.codefactor.io/repository/github/madeyoga/ytpy)
[](https://pepy.tech/project/ytpy)

[](https://github.com/MadeYoga/aio-ytpy/issues)
[](https://discord.gg/Y8sB4ay)
Python wrapper to extract youtube data. Simple *asynchronous* wrapper to get youtube video or playlist data.
The purpose of this project is to make it easier for developers to extract data from YouTube.
## Requirements
- Python 3.x
- [Get Google API' Credential 'API KEY'](https://developers.google.com/youtube/registering_an_application) for `YoutubeDataApiV3Client` only
## Dependencies
- urllib
- aiohttp
## Install
```bash
pip install --upgrade ytpy
```
### Usage
#### Search Video by `Keywords` without api key.
params:
- `q`, string. Search key. default: empty string.
- `max_results`
Example `Search` method (Without api key)
```py
from ytpy import YoutubeClient
import asyncio
import aiohttp
async def main(loop):
session = aiohttp.ClientSession()
client = YoutubeClient(session)
response = await client.search('chico love letter')
print(response)
await session.close()
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
```
#### Search Video by `Keywords` with YoutubeDataApiV3Client
https://developers.google.com/youtube/v3/docs/search
params:
- `q`, string. Search key. default: empty string.
- `part`, string. Valid parts: snippet, contentDetails, player, statistics, status. default: snippet.
- `type`, string. Valid types: video, playlist, channel.
Example `Search` method
```py
import os
import asyncio
import aiohttp
from ytpy import YoutubeDataApiV3Client
async def main(loop):
session = aiohttp.ClientSession()
# Pass the aiohttp client session
ayt = YoutubeDataApiV3Client(session, dev_key=os.environ["DEVELOPER_KEY"])
# test search
results = await ayt.search(q="d&e lost",
search_type="video",
max_results=1)
print(results)
await session.close()
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
loop.close()
```
### Examples
Check [examples](https://github.com/madeyoga/ytpy/tree/master/examples) for the full code example
## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests/examples as appropriate.
| ytpy | /ytpy-2021.8.17.tar.gz/ytpy-2021.8.17/README.md | README.md |
# ytr — Yandex.Translate prompt
This is a CLI for Yandex's translate service. At some point I got tired of opening the website, so I made a CLI.
https://user-images.githubusercontent.com/75225148/166159403-a018d890-f1c5-42df-bab3-1d57f991d573.mov
## Installation
```console
pipx install ytr
```
If you don't use [`pipx`](https://github.com/pypa/pipx/) yet, install with `pip`:
```console
pip install ytr
```
## Usage
Just run `ytr`.
By default it uses `en` and `ru` language hints. You can override this behaviour with `--hints` flag, for example, `ytr --hints en de`.
That's it: enjoy!
| ytr | /ytr-0.0.1.tar.gz/ytr-0.0.1/README.md | README.md |
import uuid
from typing import Any, TypedDict
import click
import httpx
import rich
import rich.traceback
import typer
from rich.console import Console
from rich.panel import Panel
def _raise_for_status_hook(response: httpx.Response) -> None:
response.raise_for_status()
def get_client(transport: httpx.BaseTransport | None = None) -> httpx.Client:
return httpx.Client(
base_url="https://translate.yandex.net/api/v1/tr.json",
params={"ucid": str(uuid.uuid1()).replace("-", ""), "srv": "android"},
headers={
"Accept": "application/json",
"User-Agent": "ru.yandex.translate/3.20.2024",
},
event_hooks={"response": [_raise_for_status_hook]},
transport=transport, # pyright: ignore[reportGeneralTypeIssues]
)
LangPair = tuple[str, str]
def _get_detect_params(languages: LangPair, text: str) -> dict[str, Any]:
return {"text": text, "hint": languages}
def _parse_detect_response(response: dict[str, Any]) -> str:
assert response.get("code") == 200, f"`code` is not 200: {response}"
assert response.get("lang"), f"`lang` not in response: {response}"
return response["lang"]
def detect(client: httpx.Client, languages: LangPair, text: str) -> str:
params = _get_detect_params(languages=languages, text=text)
response = client.get( # pyright: ignore[reportUnknownMemberType]
"/detect", params=params
).json()
return _parse_detect_response(response)
def _get_translate_params(from_: str, to: str) -> dict[str, str]:
return {"lang": f"{from_}-{to}", "format": "text"}
def _get_translate_form_data(text: str) -> dict[str, str]:
return {"text": text}
def _parse_translate_response(response: dict[str, Any]) -> str:
assert response.get("code") == 200, f"`code` is not 200: {response}"
assert response.get("text"), f"`text` not in response: {response}"
return response["text"][0]
def translate(client: httpx.Client, from_: str, to: str, text: str) -> str:
params = _get_translate_params(from_=from_, to=to)
form = _get_translate_form_data(text=text)
response = client.post( # pyright: ignore[reportUnknownMemberType]
"/translate", params=params, data=form
).json()
return _parse_translate_response(response)
def _resolve_destination_lang(languages: LangPair, from_: str) -> str:
if from_ not in languages:
return languages[1]
return languages[1] if languages[0] == from_ else languages[0]
class DetectAndTranslateResponse(TypedDict):
from_: str
to: str
text: str
translated: str
def detect_and_translate(
client: httpx.Client, languages: LangPair, text: str
) -> DetectAndTranslateResponse:
from_ = detect(client=client, languages=languages, text=text)
to = _resolve_destination_lang(languages=languages, from_=from_)
translated = translate(client=client, from_=from_, to=to, text=text)
return {"from_": from_, "to": to, "text": text, "translated": translated}
def _run_once(languages: LangPair, client: httpx.Client, console: Console) -> None:
console.print("[bold][bright_magenta]\n>[/bright_magenta][/bold]", end="")
text = click.prompt("", type=str, prompt_suffix="")
response = detect_and_translate(client=client, languages=languages, text=text)
console.print(
f"[italic][bright_blue]{response['from_']}[/bright_blue][/italic]",
"->",
f"[italic][bright_yellow]{response['to']}[/bright_yellow][/italic]",
)
console.print(Panel.fit(f"[bold][yellow]{response['translated']}[/yellow][/bold]"))
def _run(hints: LangPair = ("en", "ru")) -> None:
client = get_client()
console = rich.get_console()
while True:
_run_once(languages=hints, client=client, console=console)
def main() -> None:
rich.traceback.install()
typer.run(_run)
if __name__ == "__main__":
main() | ytr | /ytr-0.0.1.tar.gz/ytr-0.0.1/ytr.py | ytr.py |
.. |Build Status| image:: https://travis-ci.org/rkashapov/yandex-translator.svg?branch=master
:target: https://travis-ci.org/rkashapov/yandex-translator
.. |Coverage Status| image:: https://coveralls.io/repos/rkashapov/yandex-translator/badge.png?branch=master
:target: https://coveralls.io/r/rkashapov/yandex-translator?branch=master
Yandex translator |Build Status| |Coverage Status|
==================================================
Unofficial python client to `Yandex translator API`_.
.. _Yandex translator API: http://translate.yandex.com/
Javascript client written by `Emmanuel Odeke`_ for node.js you can find `here`_.
.. _here: https://github.com/odeke-em/ytrans.js
.. _Emmanuel Odeke: https://github.com/odeke-em/
Installation
------------
* Note: it runs on python versions >= 2.7:
``pip install ytrans``
Settings
--------
+ To use this package, you need access to the Yandex translation service via an API key.
* You can get your key here: `GET API Key`_
.. _GET API Key: http://api.yandex.com/key/form.xml?service=trnsl
+ With your API key, create a file and in it set your API key in this format:
``key=<API_KEY>``
+ To finish off, set the environment variable YANDEX_TRANSLATOR_KEY,
that contains the path to this file. Do this in your shell, .bash_profile or .bash_rc file:
``export YANDEX_TRANSLATOR_KEY=path_to_key``
Usage
-----
This package provides a cli tool as well as an interactive translator.
* Cli tool usage:
``ytranslate.py -h``
* Interactive translator:
``ytrans-interactive.py``
| ytrans | /ytrans-0.1.1.tar.gz/ytrans-0.1.1/README.rst | README.rst |
.. _contributing:
Contributing to ytree
=====================
ytree is a community project and it will be better with your
contribution.
Contributions are welcome in the form of code, documentation, or
just about anything. If you're interested in getting involved,
please do!
ytree is developed using the same conventions as yt. The `yt
Developer Guide <http://yt-project.org/docs/dev/developing/index.html>`_
is a good reference for code style, communication with other developers,
working with git, and issuing pull requests. For information specific
to ytree, such as testing and adding support for new file formats, see
the `ytree Developer Guide
<http://ytree.readthedocs.io/en/latest/Developing.html>`__.
If you'd like to know more, contact Britton Smith ([email protected])
or come by the #ytree channel on the `yt project Slack
<https://yt-project.org/slack.html>`__.
You can also find help on the `yt developers list
<http://lists.spacepope.org/listinfo.cgi/yt-users-spacepope.org>`_.
| ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/CONTRIBUTING.rst | CONTRIBUTING.rst |
Citing ytree
============
If you use ytree in your work, please cite the following:
Smith et al., (2019). ytree: A Python package for analyzing merger
trees. Journal of Open Source Software, 4(44), 1881,
https://doi.org/10.21105/joss.01881
For BibTeX users:
::
@article{ytree,
doi = {10.21105/joss.01881},
url = {https://doi.org/10.21105/joss.01881},
year = {2019},
month = {dec},
publisher = {The Open Journal},
volume = {4},
number = {44},
pages = {1881},
author = {Britton D. Smith and Meagan Lang},
title = {ytree: A Python package for analyzing merger trees},
journal = {Journal of Open Source Software}
}
If you would like to also cite the specific version of ``ytree`` used in
your work, include the following reference:
::
@software{britton_smith_2021_5336665,
author = {Britton Smith and
Meagan Lang and
Juanjo Bazán},
title = {ytree-project/ytree: ytree 3.1 Release},
month = aug,
year = 2021,
publisher = {Zenodo},
version = {ytree-3.1.0},
doi = {10.5281/zenodo.5336665},
url = {https://doi.org/10.5281/zenodo.5336665}
}
| ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/CITATION.rst | CITATION.rst |
# ytree
[](https://circleci.com/gh/ytree-project/ytree/tree/main)
[](https://codecov.io/gh/ytree-project/ytree)
[](http://ytree.readthedocs.io/en/latest/?badge=latest)
[](https://badge.fury.io/py/ytree)
[](https://doi.org/10.21105/joss.01881)
[](https://yt-project.org)
This is `ytree`, a [yt](https://github.com/yt-project/yt) extension for
working with merger tree data.
Structure formation in cosmology proceeds in a hierarchical fashion,
where dark matter halos grow via mergers with other halos. This type
of evolution can be conceptualized as a tree, with small branches
connecting to successively larger ones, and finally to the trunk. A
merger tree describes the growth of halos in a cosmological
simulation by linking a halo appearing in a given snapshot to its
direct ancestors in a previous snapshot and its descendent in the next
snapshot.
Merger trees are computationally expensive to generate and a great
number of codes exist for computing them. However, each of these codes
saves the resulting data to a different format. `ytree` is Python
package for reading and working with merger tree data from multiple
formats. If you are already familiar with using
[yt](https://github.com/yt-project/yt) to analyze snapshots from
cosmological simulations, then think of `ytree` as the `yt` of merger
trees.
To load a merger tree data set with `ytree` and print the masses of
all the halos in a single tree, one could do:
```
>>> import ytree
>>> a = ytree.load('tree_0_0_0.dat')
>>> my_tree = a[0]
>>> print(my_tree['tree', 'mass'].to('Msun'))
[6.57410072e+14 6.57410072e+14 6.53956835e+14 6.50071942e+14 ...
2.60575540e+12 2.17122302e+12 2.17122302e+12] Msun
```
A list of all currently supported formats can be found in the online
[documentation](https://ytree.readthedocs.io/en/latest/Arbor.html#loading-merger-tree-data). If
you would like to see support added for another format, we would be
happy to work with you to make it happen. In principle, any type of
tree-like data where an object has one or more ancestors and a single
descendent can be supported.
## Installation
`ytree` can be installed with pip:
```
pip install ytree
```
To get the development version, clone this repository and install like this:
```
git clone https://github.com/ytree-project/ytree
cd ytree
pip install -e .
```
## Getting Started
The [ytree documentation](https://ytree.readthedocs.io) will walk you
through installation, get you started analyzing merger trees, and help
you become a contributor to the project. Have a look!
## Sample Data
Sample data for all merger tree formats supported by `ytree` is available on the
[yt Hub](https://girder.hub.yt/) in the
[ytree data](https://girder.hub.yt/#collection/59835a1ee2a67400016a2cda) collection.
## Contributing
`ytree` would be much better with your contribution! As an extension of
[the yt Project](https://yt-project.org/), we follow the yt
[guidelines for contributing](https://github.com/yt-project/yt#contributing).
## Citing `ytree`
If you use `ytree` in your work, please cite the following:
```
Smith et al., (2019). ytree: A Python package for analyzing merger trees.
Journal of Open Source Software, 4(44), 1881,
https://doi.org/10.21105/joss.01881
```
For BibTeX users:
```
@article{ytree,
doi = {10.21105/joss.01881},
url = {https://doi.org/10.21105/joss.01881},
year = {2019},
month = {dec},
publisher = {The Open Journal},
volume = {4},
number = {44},
pages = {1881},
author = {Britton D. Smith and Meagan Lang},
title = {ytree: A Python package for analyzing merger trees},
journal = {Journal of Open Source Software}
}
```
If you would like to also cite the specific version of `ytree` used in
your work, include the following reference:
```
@software{britton_smith_2021_5336665,
author = {Britton Smith and
Meagan Lang and
Juanjo Bazán},
title = {ytree-project/ytree: ytree 3.1 Release},
month = aug,
year = 2021,
publisher = {Zenodo},
version = {ytree-3.1.0},
doi = {10.5281/zenodo.5336665},
url = {https://doi.org/10.5281/zenodo.5336665}
}
```
## Resources
* The latest documentation can be found at
https://ytree.readthedocs.io.
* The [ytree
paper](https://joss.theoj.org/papers/10.21105/joss.01881) in the
[Journal of Open Source Software](https://joss.theoj.org/).
* `ytree` is an extension of [the yt
Project](https://yt-project.org/). The [yt-project community
resources](https://github.com/yt-project/yt#resources) can be used
for ytree-related communication. The `ytree` developers can usually
be found on the yt project Slack channel.
| ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/README.md | README.md |
# ytree Community Code of Conduct
The community of participants in open source Scientific projects is
made up of members from around the globe with a diverse set of skills,
personalities, and experiences. It is through these differences that
our community experiences success and continued growth. We expect
everyone in our community to follow these guidelines when interacting
with others both inside and outside of our community. Our goal is to
keep ours a positive, inclusive, successful, and growing community.
As members of the community,
* We pledge to treat all people with respect and provide a harassment-
and bullying-free environment, regardless of sex, sexual orientation
and/or gender identity, disability, physical appearance, body size,
race, nationality, ethnicity, and religion. In particular, sexual
language and imagery, sexist, racist, or otherwise exclusionary
jokes are not appropriate.
* We pledge to respect the work of others by recognizing
acknowledgment/citation requests of original authors. As authors, we
pledge to be explicit about how we want our own work to be cited or
acknowledged.
* We pledge to welcome those interested in joining the community, and
realize that including people with a variety of opinions and
backgrounds will only serve to enrich our community. In particular,
discussions relating to pros/cons of various technologies,
programming languages, and so on are welcome, but these should be
done with respect, taking proactive measure to ensure that all
participants are heard and feel confident that they can freely
express their opinions.
* We pledge to welcome questions and answer them respectfully, paying
particular attention to those new to the community. We pledge to
provide respectful criticisms and feedback in forums, especially in
discussion threads resulting from code contributions.
* We pledge to be conscientious of the perceptions of the wider
community and to respond to criticism respectfully. We will strive
to model behaviors that encourage productive debate and
disagreement, both within our community and where we are
criticized. We will treat those outside our community with the same
respect as people within our community.
We pledge to help the entire community follow the code of conduct, and
to not remain silent when we see violations of the code of conduct. We
will take action when members of our community violate this code such
as contacting the project manager, Britton Smith
([email protected]). All emails will be treated with the strictest
confidence or talking privately with the person.
This code of conduct applies to all community situations online and
offline, including mailing lists, forums, social media, conferences,
meetings, associated social events, and one-to-one interactions.
This Community Code of Conduct comes the
<a href="http://yt-project.org/community.html"> yt Community Code
of Conduct</a>, which was adapted from the
<a href="http://www.astropy.org/about.html#codeofconduct"> Astropy
Community Code of Conduct</a>, which was partially inspired by the PSF
code of conduct.
| ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/CODE_OF_CONDUCT.md | CODE_OF_CONDUCT.md |
.. _sample-data:
Sample Data
===========
Sample datasets for every supported data format are available for download
from the `yt Hub <https://girder.hub.yt/>`__ in the
`ytree data <https://girder.hub.yt/#collection/59835a1ee2a67400016a2cda>`__
collection. The entire collection (about 979 MB) can be downloaded
via the yt Hub's web interface by clicking on "Actions" drop-down menu on
the far right and selecting "Download collection." Individual datasets can
also be downloaded from this interface. Finally, the entire collection can
be downloaded through the girder-client interface:
.. code-block:: bash
$ pip install girder-client
$ girder-cli --api-url https://girder.hub.yt/api/v1 download 59835a1ee2a67400016a2cda ytree_data
| ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/doc/source/Data.rst | Data.rst |
.. _ytree_parallel:
Parallel Computing with ytree
=============================
``ytree`` provides functions for iterating over trees and nodes in
parallel. Underneath, they make use of the
:func:`~yt.utilities.parallel_tools.parallel_analysis_interface.parallel_objects`
function in ``yt``. This functionality is built on `MPI
<https://en.wikipedia.org/wiki/Message_Passing_Interface>`__, so it
can be used to parallelize analysis across multiple nodes of a
distributed computing system.
.. note:: Before reading this section, consult the
:ref:`parallel-computation` section of the ``yt`` documentation to
learn how to configure ``yt`` for running in parallel.
Enabling Parallelism and Running in Parallel
--------------------------------------------
All parallel computation in ``yt`` (and hence, ``ytree``) begins by
importing ``yt`` and calling the
:func:`~yt.utilities.parallel_tools.parallel_analysis_interface.enable_parallelism`
function.
.. code-block:: python
import yt
yt.enable_parallelism()
import ytree
In all cases, scripts must be run with ``mpirun`` to work in
parallel. For example, to run on 4 processors, do:
.. code-block:: bash
$ mpirun -np 4 python my_analysis.py
where "my_analysis.py" is the name of the script.
.. _parallel_iterators:
Parallel Iterators
------------------
The three parallel iterator functions discussed below are designed to
work in conjunction with analysis that makes use of
:ref:`analysis-fields`. Minimally, they can be used to iterate over
trees and nodes in parallel, but their main advantage is that they
will handle the gathering and organization of new analysis field
values so they can be properly saved and reloaded. The most efficient
function to use will depend on the nature of your analysis.
In the examples below, the "analysis" performed will be
facilitated through an :ref:`analysis field <analysis-fields>`, called
"test_field". The following should be assumed to happen before all the
examples.
.. code-block:: python
import yt
yt.enable_parallelism()
import ytree
a = ytree.load("arbor/arbor.h5")
if "test_field" not in a.field_list:
a.add_analysis_field("test_field", default=-1, units="Msun")
.. _tree_parallel:
Parallelizing over Trees
^^^^^^^^^^^^^^^^^^^^^^^^
The :func:`~ytree.utilities.parallel.parallel_trees` function will
distribute a list of trees to be analyzed over all available
processors. Each processor will work on a single tree in
serial.
.. code-block:: python
trees = list(a[:])
for tree in ytree.parallel_trees(trees):
for node in tree["forest"]:
node["test_field"] = 2 * node["mass"] # this is our analysis
At the end of the outer loop, the new values for "test_field" will be
collected on the root process (i.e., the process with rank 0) and the
arbor will be saved with
:func:`~ytree.data_structures.save_arbor.save_arbor`. No additional
code is required for the new analysis field values to be collected.
By default, each processor will be allocated an equal number of
trees. However, this can lead to an unbalanced load if the amount of
work varies significantly for each tree. By including the
``dynamic=True`` keyword, trees will be allocated using a task queue,
where each processor is only given another tree after it finishes
one. Note, though, that the total number of working processes is one
fewer than the number being run with as one will act as the server for
the task queue.
.. code-block:: python
trees = list(a[:])
for tree in ytree.parallel_trees(trees, dynamic=True):
for node in tree["forest"]:
node["test_field"] = 2 * node["mass"] # this is our analysis
For various reasons, it may be useful to save results after a certain
number of loop iterations rather than only once at the very end. The
analysis may take a long time, requiring scripts to be restarted, or
keeping results for many trees in memory may be prohibitive. The
``save_every`` keyword can be used to specify a number of iterations
before results are saved. The example below will save results every 8
iterations.
.. code-block:: python
trees = list(a[:])
for tree in ytree.parallel_trees(trees, save_every=8):
for node in tree["forest"]:
node["test_field"] = 2 * node["mass"] # this is our analysis
The default behavior will allocate a tree to a single processor. To
allocate more than one processor to each tree, the ``njobs`` keyword
can be used to set the total number of process groups for the
loop. For example, if running with 8 total processors, setting
``njobs=4`` will create 4 groups of 2 processors each.
.. code-block:: python
trees = list(a[:])
for tree in ytree.parallel_trees(trees, njobs=4):
for node in tree["forest"]:
if yt.is_root():
node["test_field"] = 2 * node["mass"] # this is our analysis
The :func:`~yt.funcs.is_root` function can be used to determine which
process is the root in a group. Only the results recorded by the root
process will be collected. In the example above, it is up to the user
to properly manage the parallelism within the loop.
.. _tree_node_parallel:
Parallelizing over Nodes in a Single Tree
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The method presented above in :ref:`tree_parallel` works best when the
work done on each node in a tree is small compared to the total number
of trees. If the opposite is true, and either the total number of
trees is small or the work done on each node is expensive, then it may
be better to parallelize over the nodes in a single tree using the
:func:`~ytree.utilities.parallel.parallel_tree_nodes` function. The
previous example is parallelized over nodes in a tree in the following
way.
.. code-block:: python
trees = list(a[:])
for tree in trees:
for node in ytree.parallel_tree_nodes(tree):
node["test_field"] = 2 * node["mass"]
if yt.is_root():
a.save_arbor(trees=trees)
Unlike the :func:`~ytree.utilities.parallel.parallel_trees` and
:func:`~ytree.utilities.parallel.parallel_nodes` functions, no
saving occurs automatically. Hence, the results must be saved
manually, as in the above example.
The ``group`` keyword can be set to ``forest`` (the default),
``tree``, or ``prog`` to control which nodes of the tree are looped
over. The ``dynamic`` and ``njobs`` keywords have similar behavior as
in :ref:`tree_parallel`.
.. _node_parallel:
Parallelizing over Nodes in a List of Trees
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The previous two examples use a nested loop structure, parallelizing
either the outer loop over trees or the inner loop over nodes in a
given tree. The :func:`~ytree.utilities.parallel.parallel_nodes`
function combines these into a single iterator capable of adding
parallelism to either the loop over trees, nodes in a tree, or
both. With this function, the same example from above becomes:
.. code-block:: python
trees = list(a[:])
for node in ytree.parallel_nodes(trees):
node["test_field"] = 2 * node["mass"]
New analysis field values are collected and saved automatically as
with the :func:`~ytree.utilities.parallel.parallel_trees`
function. Similar to :func:`~ytree.utilities.parallel.parallel_trees`,
the ``save_every`` keyword can be used to control the number of full
trees to be completed before saving results. As well, the ``group``
keyword can be used to control the nodes iterated over in a tree,
similar to how it works in
:func:`~ytree.utilities.parallel.parallel_tree_nodes`. You will likely
be unsurprised to learn that the
:func:`~ytree.utilities.parallel.parallel_nodes` function is
implemented using nested calls to
:func:`~ytree.utilities.parallel.parallel_trees` and
:func:`~ytree.utilities.parallel.parallel_tree_nodes`.
The ``dynamic`` and ``njobs`` keywords also work similarly, only that
they must be specified as tuples of length 2, where the first values
control the loop over trees and the second values control the loop
over nodes in a tree. Using this, it is possible to enable task queues
for both loops (trees and nodes), as in the following example.
.. code-block:: python
trees = list(a[:])
for node in ytree.parallel_nodes(trees, save_every=8,
njobs=(3, 0),
dynamic=(True, True)):
node["test_field"] = 2 * node["mass"]
If the above example is run with 13 processors, the result will be a
task queue with 3 process groups of 4 processors each. Each of those
process groups will work on a single tree using its own task queue,
consisting of 1 server process and 3 worker processes. What a world we
live in.
| ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/doc/source/Parallelism.rst | Parallelism.rst |
.. _examples:
Example Applications
====================
Below are some examples of things one might want to do with merger
trees that demonstrate various ``ytree`` functions. If you have made
something interesting, please add it!
Halo Age (a50)
--------------
One way to define the age of a halo is by calculating the scale factor
when it reached 50% of its current mass. This is often referred to as
"a50". In the example below, this is calculated by linearly
interpolating from the mass of the main progenitor.
.. code-block:: python
import numpy as np
def calc_a50(node):
# main progenitor masses
pmass = node["prog", "mass"]
mh = 0.5 * node["mass"]
m50 = pmass <= mh
if not m50.any():
ah = node["scale_factor"]
else:
pscale = node["prog", "scale_factor"]
# linearly interpolate
i = np.where(m50)[0][0]
slope = (pscale[i-1] - pscale[i]) / (pmass[i-1] - pmass[i])
ah = slope * (mh - pmass[i]) + pscale[i]
node["a50"] = ah
Now we'll run it using the :ref:`analysis_pipeline`.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("consistent_trees/tree_0_0_0.dat")
>>> a.add_analysis_field("a50", "")
>>> ap = ytree.AnalysisPipeline()
>>> ap.add_operation(calc_a50)
>>> trees = list(a[:])
>>> for tree in trees:
... ap.process_target(tree)
>>> fn = a.save_arbor(filename="halo_age", trees=trees)
>>> a2 = ytree.load(fn)
>>> print (a2[0]["a50"])
0.57977664
Significance
------------
Brought to you by John Wise, a halo's significance is calculated by
recursively summing over all ancestors the mass multiplied by the time
between snapshots. When determining the main progenitor of a halo, the
significance measure will select for the ancestor with the deeper
history instead of just the higher mass. This can be helpful in cases
of near 1:1 mergers.
Below, we define a function that calculates the significance
for every halo in a single tree.
.. code-block:: python
def calc_significance(node):
if node.descendent is None:
dt = 0. * node["time"]
else:
dt = node.descendent["time"] - node["time"]
sig = node["mass"] * dt
if node.ancestors is not None:
for anc in node.ancestors:
sig += calc_significance(anc)
node["significance"] = sig
return sig
Now, we'll use the :ref:`analysis_pipeline` to calculate the
significance for all trees and save a new dataset. After loading the
new arbor, we use the
:func:`~ytree.data_structures.arbor.Arbor.set_selector` function to
use the new significance field to determine the progenitor line.
.. code-block:: python
>>> a = ytree.load("tiny_ctrees/locations.dat")
>>> a.add_analysis_field("significance", "Msun*Myr")
>>> ap = ytree.AnalysisPipeline()
>>> ap.add_operation(calc_significance)
>>> trees = list(a[:])
>>> for tree in trees:
... ap.process_target(tree)
>>> fn = a.save_arbor(filename="significance", trees=trees)
>>> a2 = ytree.load(fn)
>>> a2.set_selector("max_field_value", "significance")
>>> prog = list(a2[0]["prog"])
>>> print (prog)
[TreeNode[1457223360], TreeNode[1452164856], TreeNode[1447024182], ...
TreeNode[6063823], TreeNode[5544219], TreeNode[5057761]] | ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/doc/source/Examples.rst | Examples.rst |
.. _developing:
Developer Guide
===============
``ytree`` is developed using the same conventions as yt. The `yt
Developer Guide <http://yt-project.org/docs/dev/developing/index.html>`_
is a good reference for code style, communication with other developers,
working with git, and issuing pull requests. Below is a brief guide of
aspects that are specific to ``ytree``.
Contributing in a Nutshell
--------------------------
Step zero, get out of that nutshell!
After that, the process for making contributions to ``ytree`` is roughly as
follows:
1. Fork the `main ytree repository <https://github.com/ytree-project/ytree>`__.
2. Create a new branch.
3. Make changes.
4. Run tests. Return to step 3, if needed.
5. Issue pull request.
The `yt Developer Guide
<https://yt-project.org/docs/dev/developing/index.html>`__ and
`github <https://github.com/>`__ documentation will help with the
mechanics of git and pull requests.
Testing
-------
The ``ytree`` source comes with a series of tests that can be run to
ensure nothing unexpected happens after changes have been made. These
tests will automatically run when a pull request is issued or updated,
but they can also be run locally very easily. At present, the suite
of tests for ``ytree`` takes about three minutes to run.
Testing Data
^^^^^^^^^^^^
The first order of business is to obtain the sample datasets. See
:ref:`sample-data` for how to do so. Next, ``ytree`` must be configure to
know the location of this data. This is done by creating a configuration
file in your home directory at the location ``~/.config/ytree/ytreerc``.
.. code-block:: bash
$ mkdir -p ~/.config/ytree
$ echo [ytree] > ~/.config/ytree/ytreerc
$ echo test_data_dir = /Users/britton/ytree_data >> ~/.config/ytree/ytreerc
$ cat ~/.config/ytree/ytreerc
[ytree]
test_data_dir = /Users/britton/ytree_data
This path should point to the outer directory containing all the
sample datasets.
Installing Development Dependencies
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A number of additional packages are required for testing. These can be
installed with pip from within the ``ytree`` source by doing:
.. code-block:: bash
$ pip install -e .[dev]
To see how these dependencies are defined, have a look at the
``extras_require`` keyword argument in the ``setup.py`` file.
Run the Tests
^^^^^^^^^^^^^
The tests are run from the top level of the ``ytree`` source.
.. code-block:: bash
$ pytest tests
============================= test session starts ==============================
platform darwin -- Python 3.6.0, pytest-3.0.7, py-1.4.32, pluggy-0.4.0
rootdir: /Users/britton/Documents/work/yt/extensions/ytree/ytree, inifile:
collected 16 items
tests/test_arbors.py ........
tests/test_flake8.py .
tests/test_saving.py ...
tests/test_treefarm.py ..
tests/test_ytree_1x.py ..
========================= 16 passed in 185.03 seconds ==========================
Adding Support for a New Format
-------------------------------
The :class:`~ytree.data_structures.arbor.Arbor` class is reasonably
generalized such that adding support for a new file format
should be relatively straightforward. The existing frontends
also provide guidance for what must be done. Below is a brief
guide for how to proceed. If you are interested in doing this,
we will be more than happy to help!
Where do the files go?
^^^^^^^^^^^^^^^^^^^^^^
As in yt, the code specific to one file format is referred to as a
"frontend". Within the ``ytree`` source, each frontend is located in
its own directory within ``ytree/frontends``. Name your
directory using lowercase and underscores and put it in there.
To allow your frontend to be directly importable at run-time, add
the name to the ``_frontends`` list in ``ytree/frontends/api.py``.
Building Your Frontend
^^^^^^^^^^^^^^^^^^^^^^
A very good way to build a new frontend is to start with an
existing frontend for a similar type of dataset. To see the variety
of examples, consult the :ref:`internal-classes` section of the
:ref:`api-reference`.
To build a new frontend, you will need to make frontend-specific
subclasses for a few components. A straightforward way to do this
is to start with the script below, loading your data with it. Each
line will run correctly after a distinct phase of the implementation
is completed. As you progress, the next function needing implemented
will raise a ``NotImplementedError`` exception, indicating what
should be done next.
.. code-block:: python
import ytree
# Arbor subclass with working _is_valid function
a = ytree.load(<your data>)
# Recognizing the available fields
print (a.field_list)
# Calculate the number of trees in the dataset
print (a.size)
# Create root TreeNode objects
my_tree = a[0]
print (my_tree)
# Query fields for individual trees
print (my_tree['mass'])
# Query fields for a whole tree
print (my_tree['tree', 'mass'])
# Create TreeNodes for whole tree
for node in my_tree['tree']:
print (node)
# Query fields for all root nodes
print (a['mass'])
# Putting it all together
a.save_arbor()
The components and the files in which they belong are:
1. The :class:`~ytree.data_structures.arbor.Arbor` itself (``arbor.py``).
2. The file i/o (``io.py``).
3. Recognizing frontend-specific fields (``fields.py``).
In addition to this, you will need to add a file called ``__init__.py``,
which will allow your code to be imported. This file should minimally
import the frontend-specific :class:`~ytree.data_structures.arbor.Arbor`
class. For example, the consistent-trees ``__init__.py`` looks like this:
.. code-block:: python
from ytree.frontends.consistent_trees.arbor import \
ConsistentTreesArbor
The ``_is_valid`` Function
^^^^^^^^^^^^^^^^^^^^^^^^^^
Within every :class:`~ytree.data_structures.arbor.Arbor` subclass should
appear a method called ``_is_valid``. This function is used by
:func:`~ytree.data_structures.load` to determine if the provided file is
the correct type. This function can examine the file's naming convention
and/or open it and inspect its contents, whatever is required to uniquely
identify your frontend. Have a look at the various examples.
Two Types of Arbors
^^^^^^^^^^^^^^^^^^^
There are generally two types of merger tree data that ``ytree``
ingests:
1. all merger tree data (full trees, halos, etc.) contained within
a single file. These include the ``consistent-trees``,
``consistent-trees-hdf5``, ``lhalotree``, and ``ytree`` frontends.
2. halos in files grouped by redshift (halo catalogs) that contain
the halo id for the descendent halo which lives in the next catalog.
An example of this is the ``rockstar`` frontend.
Depending on your case, different base classes should be subclassed.
This is discussed below. There are also hybrid formats that use
both merger tree and halo catalog files together. An example of this
is the ``ahf`` (Amiga Halo Finder) frontend.
Merger Tree Data in One File (or a few)
#######################################
If this is your case, then the consistent-trees and "ytree" frontends
are the best examples to follow.
In ``arbor.py``, your subclass of :class:`~ytree.data_structures.arbor.Arbor`
should implement two functions, ``_parse_parameter_file`` and ``_plant_trees``.
``_parse_parameter_file``: This is the first thing called when your
dataset is loaded. It is responsible for determining things like
box size, cosmological parameters, and the list of fields.
``_plant_trees``: This function is responsible for creating arrays
of the data required to build all the root
:class:`~ytree.data_structures.tree_node.TreeNode` objects in the
:class:`~ytree.data_structures.arbor.Arbor`. The names of these
attributes are declared in the ``_node_io_attrs`` attribute. For
example, the
:class:`~ytree.frontends.consistent_trees_hdf5.arbor.ConsistentTreesHDF5Arbor`
class names three required attributes: ``_fi``, the data file number in
which this tree lives; ``_si``, the starting index of the section in the
data array corresponding to this tree; and ``_ei``, the ending index in
the data array.
In ``io.py``, you will implement the machinery responsible for
reading field data from disk. You must create a subclass of
the :class:`~ytree.data_structures.io.TreeFieldIO` class and implement
the ``_read_fields`` function. This function accepts a single
root node (a ``TreeNode`` that is the root of a tree) and a list
of fields and should return a dictionary of NumPy arrays for each field.
Halo Catalog-style Data
#######################
If this is your case, then the rockstar and treefarm frontends
are the best examples to follow.
For this type of data, you will subclass the
:class:`~ytree.data_structures.arbor.CatalogArbor` class, which is itself a
subclass of :class:`~ytree.data_structures.arbor.Arbor` designed for this
type of data.
In ``arbor.py``, your subclass should implement two functions,
``_parse_parameter_file`` and ``_get_data_files``. The purpose of
``_parse_parameter_file`` is described above.
``_get_data_files``: This type of data is usually loaded by
providing one of the set of files. This function needs to figure
out how many other files there are and their names and construct a
list to be saved.
In ``io.py``, you will create a subclass of
:class:`~ytree.data_structures.io.CatalogDataFile` and implement two functions:
``_parse_header`` and ``_read_fields``.
``_parse_header``: This function reads any metadata specific to this
halo catalog. For exmaple, you might get the current redshift here.
``_read_fields``: This function is responsible for reading field
data from disk. This should minimally take a list of fields and
return a dictionary with NumPy arrays for each field for all halos
contained in the file. It should also, optionally, take a list of
:class:`~ytree.data_structures.tree_node.TreeNode` instances and return fields
only for them.
Field Units and Aliases (``fields.py``)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The :class:`~ytree.data_structures.fields.FieldInfoContainer` class holds
information about field names and units. Your subclass can define
two tuples, ``known_fields`` and ``alias_fields``. The
``known_fields`` tuple is used to set units for fields on disk.
This is useful especially if there is no way to get this information
from the file. The convention for each entry is (name on disk, units).
By creating aliases to standardized names, scripts can be run on
multiple types of data with little or no alteration for
frontend-specific field names. This is done with the ``alias_fields``
tuple. The convention for each entry is (alias name, name on disk,
field units).
.. code-block:: python
from ytree.data_structures.fields import \
FieldInfoContainer
class NewCodeFieldInfo(FieldInfoContainer):
known_fields = (
# name on disk, units
("Mass", "Msun/h"),
("PX", "kpc/h"),
)
alias_fields = (
# alias name, name on disk, units for alias
("mass", "Mass", "Msun"),
("position_x", "PX", "Mpc/h"),
...
)
You made it!
^^^^^^^^^^^^
That's all there is to it! Now you too can do whatever it is
people do with merger trees. There are probably important things
that were left out of this document. If you find any, please consider
making an addition or opening an issue. If you're stuck anywhere,
don't hesitate to ask for help. If you've gotten this far, we
really want to see you make it to the finish!
Everyone Loves Samples
^^^^^^^^^^^^^^^^^^^^^^
It would be especially great if you could provide a small sample dataset
with your new frontend, something less than a few hundred MB if possible.
This will ensure that your new frontend never gets broken and
will also help new users get started. Once you have some data, make an
addition to the arbor tests by following the example in
``tests/test_arbors.py``. Then, contact Britton Smith to arrange for
your sample data to be added to the `ytree data
<https://girder.hub.yt/#collection/59835a1ee2a67400016a2cda>`__
collection on the `yt Hub <https://girder.hub.yt/>`__.
Ok, now you're totally done. Take the rest of the afternoon off.
| ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/doc/source/Developing.rst | Developing.rst |
.. _arbor:
Working with Merger Trees
=========================
The :class:`~ytree.data_structures.arbor.Arbor` class is responsible for loading
and providing access to merger tree data. In this document, a loaded merger tree
dataset is referred to as an **arbor**. ``ytree`` provides several different
ways to navigate, query, and analyze merger trees. It is recommended that you
read this entire section to identify the way that is best for what you want to do.
Loading Data
------------
``ytree`` can load merger tree data from multiple sources using
the :func:`~ytree.data_structures.load.load` command.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("consistent_trees/tree_0_0_0.dat")
This command will determine the correct format and read in the data
accordingly. For examples of loading each format, see below.
.. toctree::
:maxdepth: 2
Loading
Getting Started with Merger Trees
---------------------------------
Very little happens immediately after a dataset has been loaded. All tree
construction and data access occurs only on demand. After loading,
information such as the simulation box size, cosmological parameters, and
the available fields can be accessed.
.. code-block:: python
>>> print (a.box_size)
100.0 Mpc/h
>>> print (a.hubble_constant, a.omega_matter, a.omega_lambda)
0.695 0.285 0.715
>>> print (a.field_list)
['scale', 'id', 'desc_scale', 'desc_id', 'num_prog', ...]
Similar to `yt <http://yt-project.org/docs/dev/analyzing/fields.html>`__,
``ytree`` supports accessing fields by their native names as well as generalized
aliases. For more information on fields in ``ytree``, see :ref:`fields`.
How many trees are there?
^^^^^^^^^^^^^^^^^^^^^^^^^
The total number of trees in the arbor can be found using the ``size``
attribute. As soon as any information about the collection of trees within the
loaded dataset is requested, arrays will be created containing the metadata
required for generating the root nodes of every tree.
.. code-block:: python
>>> print (a.size)
Loading tree roots: 100%|██████| 5105985/5105985 [00:00<00:00, 505656111.95it/s]
327
Root Fields
^^^^^^^^^^^
Field data for all tree roots is accessed by querying the
:class:`~ytree.data_structures.arbor.Arbor` in a
dictionary-like manner.
.. code-block:: python
>>> print (a["mass"])
Getting root fields: 100%|██████████████████| 327/327 [00:00<00:00, 9108.67it/s]
[ 6.57410072e+14 5.28489209e+14 5.18129496e+14 4.88920863e+14, ...,
8.68489209e+11 8.68489209e+11 8.68489209e+11] Msun
``ytree`` uses the `unyt <https://unyt.readthedocs.io/>`__ package for symbolic units
on NumPy arrays.
.. code-block:: python
>>> print (a["virial_radius"].to("Mpc/h"))
[ 1.583027 1.471894 1.462154 1.434253 1.354779 1.341322 1.28617, ...,
0.173696 0.173696 0.173696 0.173696 0.173696] Mpc/h
When dealing with cosmological simulations, care must be taken to distinguish
between comoving and proper reference frames. Please read :ref:`frames` before
your magical ``ytree`` journey begins.
Accessing Individual Trees
^^^^^^^^^^^^^^^^^^^^^^^^^^
Individual trees can be accessed by indexing the
:class:`~ytree.data_structures.arbor.Arbor` object.
.. code-block:: python
>>> print (a[0])
TreeNode[12900]
A :class:`~ytree.data_structures.tree_node.TreeNode` is one halo in a merger tree.
The number is the universal identifier associated with halo. It is unique
to the whole arbor. Fields can be accessed for any given
:class:`~ytree.data_structures.tree_node.TreeNode` in the same dictionary-like
fashion.
.. code-block:: python
>>> my_tree = a[0]
>>> print (my_tree["mass"])
657410071942446.1 Msun
Array slicing can also be used to select multiple
:class:`~ytree.data_structures.tree_node.TreeNode` objects. This will return a
generator that can be iterated over or cast to a list.
.. code-block:: python
>>> every_second_tree = list(a[::2])
>>> print (every_second_tree[0]["mass"])
657410071942446.1 Msun
Note, the :class:`~ytree.data_structures.arbor.Arbor` object does not
store individual :class:`~ytree.data_structures.tree_node.TreeNode` objects, it
only generates them. Thus, one must explicitly keep around any
:class:`~ytree.data_structures.tree_node.TreeNode` object for changes to persist.
This is illustrated below:
.. code-block:: python
>>> # this will not work
>>> a[0].thing = 5
>>> print (a[0].thing)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'TreeNode' object has no attribute 'thing'
>>> # this will work
>>> my_tree = a[0]
>>> my_tree.thing = 5
>>> print (my_tree.thing)
5
The only exception to this is computing the number of nodes in a tree. This
information will be propagated back to the
:class:`~ytree.data_structures.arbor.Arbor` as it can be expensive to compute
for large trees.
.. code-block:: python
>>> my_tree = a[0]
print (my_tree.tree_size) # call function to calculate tree size
691
>>> new_tree = a[0]
print (new_tree.tree_size) # retrieved from a cache
691
Accessing the Nodes in a Tree or Forest
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A node is defined as a single halo at a single time in a merger tree.
Throughout these docs, the words halo and node are used interchangeably.
Nodes in a given tree can be accessed in three different ways: by
:ref:`tree-access`, :ref:`forest-access`, or :ref:`progenitor-access`.
Each of these will return a generator of
:class:`~ytree.data_structures.tree_node.TreeNode` objects or field
values for all :class:`~ytree.data_structures.tree_node.TreeNode` objects
in the tree, forest, or progenitor line. To get a specific node from a
tree, see :ref:`single-node-access`.
.. note:: Access by forest is supported even for datasets that do not
group trees by forest. If you have no requirement for the order in
which nodes are to be returned, then access by forest is recommended
as it will be considerably faster than access by tree. Access by tree
is effectively a depth-first walk through the tree. This requires
additional data structures to be built, whereas forest access does
not.
.. _tree-access:
Accessing All Nodes in a Tree
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The full lineage of the tree can be accessed by querying any
:class:`~ytree.data_structures.tree_node.TreeNode` with the ``tree`` keyword.
As of ``ytree`` version 3.0, this returns a generator that can be used
to loop through all nodes in the tree.
.. code-block:: python
>>> print (my_tree["tree"])
<generator object TreeNode._tree_nodes at 0x11bbc1f20>
>>> # loop over nodes
>>> for my_node in my_tree["tree"]:
... print (my_node, my_node["mass"])
TreeNode[12900] 657410100000000.0 Msun
TreeNode[12539] 657410100000000.0 Msun
TreeNode[12166] 653956900000000.0 Msun
TreeNode[11796] 650071960000000.0 Msun
...
To store all the nodes in a single structure, convert it to a list:
>>> print (list(my_tree["tree"]))
[TreeNode[12900], TreeNode[12539], TreeNode[12166], TreeNode[11796], ...
TreeNode[591]]
Fields can be queried for the tree by including the field name.
.. code-block:: python
>>> print (my_tree["tree", "virial_radius"])
[ 2277.73669065 2290.65899281 2301.43165468 2311.47625899 2313.99280576 ...
434.59856115 410.13381295 411.25755396] kpc
The above examples will work for any halo in the tree, not just the final halo.
The full tree leading up to any given halo can be accessed in the same way.
.. code-block:: python
>>> tree_nodes = list(my_tree["tree"])
>>> # start with the 3rd halo in the above tree
>>> sub_tree = tree_nodes[2]
>>> print (list(sub_tree["tree"]))
[TreeNode[12166], TreeNode[11796], TreeNode[11431], TreeNode[11077], ...
TreeNode[591]]
>>> print (sub_tree["tree", "virial_radius"])
[2301.4316 2311.4763 2313.993 2331.413 2345.5454 2349.918 ...
434.59857 410.13382 411.25757] kpc
.. _forest-access:
Accessing All Nodes in a Forest
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The :ref:`load-ctrees-hdf5`, :ref:`load-lhalotree`, :ref:`load-lhalotree-hdf5`,
:ref:`load-moria`, :ref:`load-treefrog` formats provide access to halos grouped
by forest. A forest is a group of trees with halos that interact in a non-merging
way through processes like fly-bys.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("consistent_trees_hdf5/soa/forest.h5",
... access="forest")
>>> my_forest = a[0]
>>> # all halos in the forest
>>> print (list(my_forest["forest"]))
[TreeNode[90049568], TreeNode[88202573], TreeNode[86292249], ...
TreeNode[9272027], TreeNode[7435733], TreeNode[5768880]]
>>> # all halo masses in forest
>>> print (my_forest["forest", "mass"])
[3.38352524e+11 3.34071450e+11 3.34071450e+11 3.31709477e+11 ...
7.24092117e+09 4.34455270e+09] Msun
To find all the roots in that forest, i.e., the roots of all individual trees
contained, see :ref:`getting_root_nodes`.
Accessing a Halo's Ancestors and Descendent
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The direct ancestors of any
:class:`~ytree.data_structures.tree_node.TreeNode` object can be accessed
through the ``ancestors`` attribute.
.. code-block:: python
>>> my_ancestors = list(my_tree.ancestors)
>>> print (my_ancestors)
[TreeNode[12539]]
A halo's descendent can be accessed in a similar fashion.
.. code-block:: python
>>> print (my_ancestors[0].descendent)
TreeNode[12900]
.. _progenitor-access:
Accessing the Progenitor Lineage of a Tree
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Similar to the ``tree`` keyword, the ``prog`` keyword can be used to access
the line of main progenitors. Just as above, this returns a generator
of :class:`~ytree.data_structures.tree_node.TreeNode` objects.
.. code-block:: python
>>> print (list(my_tree["prog"]))
[TreeNode[12900], TreeNode[12539], TreeNode[12166], TreeNode[11796], ...
TreeNode[62]]
Fields for the main progenitors can be accessed just like for the whole
tree.
.. code-block:: python
>>> print (my_tree["prog", "mass"])
[ 6.57410072e+14 6.57410072e+14 6.53956835e+14 6.50071942e+14 ...
8.29496403e+13 7.72949640e+13 6.81726619e+13 5.99280576e+13] Msun
Progenitor lists and fields can be accessed for any halo in the tree.
.. code-block:: python
>>> tree_nodes = list(my_tree["tree"])
>>> # pick a random halo in the tree
>>> my_halo = tree_nodes[42]
>>> print (list(my_halo["prog"]))
[TreeNode[588], TreeNode[446], TreeNode[317], TreeNode[200], TreeNode[105],
TreeNode[62]]
>>> print (my_halo["prog", "virial_radius"])
[1404.1354 1381.4087 1392.2404 1363.2145 1310.3842 1258.0159] kpc
Customizing the Progenitor Line
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
By default, the progenitor line is defined as the line of the most
massive ancestors. This can be changed by calling the
:func:`~ytree.data_structures.arbor.Arbor.set_selector`.
.. code-block:: python
>>> a.set_selector("max_field_value", "virial_radius")
New selector functions can also be supplied. These functions should
minimally accept a list of ancestors and return a single
:class:`~ytree.data_structures.tree_node.TreeNode`.
.. code-block:: python
>>> def max_value(ancestors, field):
... vals = np.array([a[field] for a in ancestors])
... return ancestors[np.argmax(vals)]
...
>>> ytree.add_tree_node_selector("max_field_value", max_value)
>>>
>>> a.set_selector("max_field_value", "mass")
>>> my_tree = a[0]
>>> print (list(my_tree["prog"]))
.. _single-node-access:
Accessing a Single Node in a Tree
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The :func:`~ytree.data_structures.tree_node.TreeNode.get_node` functions can be
used to retrieve a single node from the forest, tree, or progenitor lists.
.. code-block:: python
>>> my_tree = a[0]
>>> my_node = my_tree.get_node("forest", 5)
This function can be called for any node in a tree. For selection by "tree" or
"prog", the index of the node returned will be relative to the calling node,
i.e., calling with 0 will return the original node. For selection by "forest",
the index is the absolute index within the entire forest and not relative to
the calling node.
Accessing the Leaf Nodes of a Tree
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The leaf nodes of a tree are the nodes with no ancestors. These are the very first
halos to form. Accessing them for any tree can be useful for semi-analytical
models or any framework where you want to start at the origins of a halo and work
forward in time. The :func:`~ytree.data_structures.tree_node.TreeNode.get_leaf_nodes`
function will return a generator of all leaf nodes of a tree's forest, tree, or
progenitor lists.
.. code-block:: python
>>> my_tree = a[0]
>>> my_leaves = my_tree.get_leaf_nodes(selector="forest")
>>> for my_leaf in my_leaves:
... print (my_leaf)
Similar to the :func:`~ytree.data_structures.tree_node.TreeNode.get_node`
function, calling :func:`~ytree.data_structures.tree_node.TreeNode.get_leaf_nodes`
with ``selector`` set to "tree" or "prog" will return only leaf nodes from the
tree for which the calling node is the head. With ``selector`` set to "forest",
the resulting leaf nodes will be all the leaf nodes in the forest, regardless of
the calling node.
.. _getting_root_nodes:
Accessing the Root Nodes of a Forest
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A forest can have multiple root nodes, i.e., nodes that have no descendent. The
:func:`~ytree.data_structures.tree_node.TreeNode.get_root_nodes` function will
return a generator of all the root nodes in the forest. This function can be called
from any tree within a forest.
.. code-block:: python
>>> my_tree = a[0]
>>> my_roots = my_tree.get_root_nodes()
>>> for my_root in my_roots:
... print (my_root)
.. _saving-trees:
Saving Arbors and Trees
-----------------------
``Arbors`` of any type can be saved to a universal file format with the
:func:`~ytree.data_structures.arbor.Arbor.save_arbor` function. These can be
reloaded with the :func:`~ytree.data_structures.load.load` command. This
format is optimized for fast tree-building and field-access and so is
recommended for most situations.
.. code-block:: python
>>> fn = a.save_arbor()
Setting up trees: 100%|███████████████████| 327/327 [00:00<00:00, 483787.45it/s]
Getting fields [1/1]: 100%|████████████████| 327/327 [00:00<00:00, 36704.51it/s]
Creating field arrays [1/1]: 100%|█| 613895/613895 [00:00<00:00, 7931878.47it/s]
>>> a2 = ytree.load(fn)
By default, all trees and all fields will be saved, but this can be
customized with the ``trees`` and ``fields`` keywords.
For convenience, individual trees can also be saved by calling
:func:`~ytree.data_structures.tree_node.TreeNode.save_tree`.
.. code-block:: python
>>> my_tree = a[0]
>>> fn = my_tree.save_tree()
Creating field arrays [1/1]: 100%|████| 4897/4897 [00:00<00:00, 13711286.17it/s]
>>> a2 = ytree.load(fn)
Searching Through Merger Trees (Accessing Like a Database)
----------------------------------------------------------
There are a couple different ways to search through a merger tree dataset to find
halos meeting various criteria, similar to the type of selection done with a
relational database. The method discussed in :ref:`select-halos` can be used with
all data loadable with ``ytree``, while the one described in :ref:`select-halos-yt`
is only available for :ref:`load-ytree`.
.. _select-halos:
Select Halos
^^^^^^^^^^^^
The :func:`~ytree.data_structures.arbor.Arbor.select_halos` function can be used to
search the :class:`~ytree.data_structures.arbor.Arbor` for halos matching a specific
set of criteria.
.. code-block:: python
>>> halos = list(a.select_halos("tree['forest', 'mass'].to('Msun') > 5e11"))
Selecting halos (found 3): 100%|███████████████| 32/32 [00:00<00:00, 107.70it/s]
>>> print (halos)
[TreeNode[1457223360], TreeNode[1457381406], TreeNode[1420495006]]
The :func:`~ytree.data_structures.arbor.Arbor.select_halos` function will return a
generator of :class:`~ytree.data_structures.tree_node.TreeNode` objects that can be
iterated over or cast to a list, as above. The function will return halos as they
are found so the user does not have to wait until the end to begin working with
them. The progress bar will continually update to report the number of matches
found.
The selection criteria string should be designed to ``eval`` correctly
with a :class:`~ytree.data_structures.tree_node.TreeNode` object, named
"tree". More complex criteria can be supplied using \& and \|.
.. code-block:: python
>>> for halo in a.select_halos("(tree['tree', 'mass'].to('Msun') > 2e11) & (tree['tree', 'redshift'] < 0.2)"):
... progenitor_pos = halo["prog", "position"]
Selecting halos (found 69): 100%|███████████████| 32/32 [00:01<00:00, 22.50it/s]
.. _select-halos-yt:
Select Halos with yt
^^^^^^^^^^^^^^^^^^^^
.. note:: This functionality only works with :ref:`load-ytree`. You will need to
:ref:`save your data in the ytree format <saving-trees>`.
The :func:`~ytree.frontends.ytree.arbor.YTreeArbor.get_yt_selection` function
provides enhanced functionality beyond the capabilities of
:func:`~ytree.data_structures.arbor.Arbor.select_halos` by loading the dataset
into `yt <https://yt-project.org/>`__. Given search criteria,
:func:`~ytree.frontends.ytree.arbor.YTreeArbor.get_yt_selection` will return a
:class:`~yt.data_objects.selection_objects.cut_region.YTCutRegion` data container
that can then be queried to get the value of any field for all halos meeting the
criteria. This :class:`~yt.data_objects.selection_objects.cut_region.YTCutRegion`
can then be used to :ref:`generate tree nodes <halos-from-selection>` or
:ref:`query fields <yt-data-containers>`.
Creating the Selection
^^^^^^^^^^^^^^^^^^^^^^
Search criteria can be provided using a series of keywords: ``above``, ``below``,
``equal``, and ``about``.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("arbor/arbor.h5")
>>> selection = a.get_yt_selection(,
... above=[("mass", 1e13, "Msun"),
... ("redshift", 0.5)])
An individual criterion should be expressed as a tuple
(e.g., ``(field, value, <units>)``), and the above keywords accept a list of those
tuples. The criteria keywords can be given together and the halos must meet all
criteria, i.e., the criteria are combined with an AND operator.
.. code-block:: python
>>> selection = a.get_yt_selection(
... below=[("mass", 1e13, "Msun")],
... above=[("redshift", 1)])
For more complex search criteria, a cut region conditional string can be
provided instead. These should be of the form described in :ref:`cut-regions`.
These cannot not be given with any of the previously mentioned keywords.
.. code-block:: python
>>> selection = a.get_yt_selection(
... conditionals=['obj["halos", "mass"] > 1e12'])
Querying the Selection
^^^^^^^^^^^^^^^^^^^^^^
The selection object returned by
:func:`~ytree.frontends.ytree.arbor.YTreeArbor.get_yt_selection` can then be
queried to get field values for all matching halos. Fields should be queried
as ``("halos", <field name>)``.
.. code-block:: python
>>> # halos with masses of 1e14 Msun +/- 5%
>>> selection = a.get_yt_selection(
about=[("mass", 1e14, "Msun", 0.05)])
>>> print (selection["halos", "redshift"])
[0.82939091 0.97172537 1.02453741 0.31893065 0.74571856 0.97172537 ...
0.50455122 0.53499009 0.18907477 0.29567248 0.31893065] dimensionless
.. _halos-from-selection:
Getting Halos from the Selection
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The :func:`~ytree.frontends.ytree.arbor.YTreeArbor.get_nodes_from_selection`
function will return a generator of
:class:`~ytree.data_structures.tree_node.TreeNode` objects for all halos
contained within the selection.
.. code-block:: python
>>> # halos with masses of 1e14 Msun +/- 5%
>>> selection = a.get_yt_selection(
about=[("mass", 1e14, "Msun", 0.05)])
>>> for node in a.get_nodes_from_selection(selector):
... print (node["prog", "mass"])
This function can generate :class:`~ytree.data_structures.tree_node.TreeNode`
objects for :ref:`any yt data container <yt-data-containers>`.
.. _yt-data-containers:
Halos and Fields from yt Data Containers
----------------------------------------
.. note:: This functionality only works with :ref:`load-ytree`. You will need to
:ref:`save your data in the ytree format <saving-trees>`.
For merger tree data in the :ref:`ytree format <load-ytree>`, the
:attr:`~ytree.frontends.ytree.arbor.YTreeArbor.ytds` attribute provides access
to the data as a `yt <https://yt-project.org/>`__ dataset. This allows one to
analyze the entire dataset using the full range of functionality provided by
``yt``. In this way, a merger tree dataset is very much like any particle dataset,
where each particle represent a halo at a single time. For example, this makes it
possible to select halos within :ref:`geometric data containers <data-objects>`,
like spheres or regions.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("arbor/arbor.h5")
>>> ds = a.ytds
>>> sphere = ds.sphere(ds.domain_center, (5, "Mpc"))
>>> print (sphere["halos", "mass"])
These data containers can then be given to the
:func:`~ytree.frontends.ytree.arbor.YTreeArbor.get_nodes_from_selection` function to
:ref:`get the tree nodes <halos-from-selection>` for all halos within the
container.
.. code-block:: python
>>> sphere = ds.sphere(ds.domain_center, (5, "Mpc"))
>>> for node in a.get_nodes_from_selection(sphere):
... print (node["position"])
| ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/doc/source/Arbor.rst | Arbor.rst |
.. _plotting:
Plotting Merger Trees
=====================
Some relatively simple visualizations of merger trees can be made with
the :class:`~ytree.visualization.tree_plot.TreePlot` command.
Additional Dependencies
-----------------------
Making merger tree plots with ``ytree`` requires the
`pydot <https://pypi.org/project/pydot/>`__ and
`graphviz <https://www.graphviz.org/>`__ packages. ``pydot`` can be
installed with ``pip`` and the
`graphviz <https://www.graphviz.org/>`__ website provides a number
of installation options.
Making Tree Plots
-----------------
The :class:`~ytree.visualization.tree_plot.TreePlot` command can be
used to create a `digraph <https://en.wikipedia.org/wiki/Directed_graph>`__
depicting halos as filled circles with sizes proportional to their mass.
The main progenitor line will be colored red.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("ahf_halos/snap_N64L16_000.parameter",
... hubble_constant=0.7)
>>> p = ytree.TreePlot(a[0], dot_kwargs={'rankdir': 'LR', 'size': '"12,4"'})
>>> p.save('tree.png')
.. image:: _images/tree.png
Plot Modifications
^^^^^^^^^^^^^^^^^^
Four :class:`~ytree.visualization.tree_plot.TreePlot` attributes can be set
to modify the default plotting behavior. These are:
- *size_field*: The field to determine the size of each circle. Default:
'mass'.
- *size_log*: Whether to scale circle sizes based on log of size field.
Default: True.
- *min_mass*: The minimum halo mass to be included in the plot. If given
as a float, units are assumed to be Msun. Default: None.
- *min_mass_ratio*: The minimum ratio between a halo's mass and the mass
of the main halo to be included in the plot. Default: None.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("ahf_halos/snap_N64L16_000.parameter",
... hubble_constant=0.7)
>>> p = ytree.TreePlot(a[0], dot_kwargs={'rankdir': 'LR', 'size': '"12,4"'})
>>> p.min_mass_ratio = 0.01
>>> p.save('tree_small.png')
.. image:: _images/tree_small.png
Customizing Node Appearance
^^^^^^^^^^^^^^^^^^^^^^^^^^^
The appearance of the nodes can be customized by providing a function that
returns a dictionary of keywords that will be used to create the ``pydot``
node. This should accept a single argument that is a
:class:`~ytree.data_structures.tree_node.TreeNode` object representing the
halo to be plotted. For example, the following function will add labels of
the halo id and mass and make the node shape square. It will also color
the most massive progenitor red.
.. code-block:: python
def my_node(halo):
prog = list(halo.find_root()['prog', 'uid'])
if halo['uid'] in prog:
color = 'red'
else:
color = 'black'
label = \
"""
id: %d
mass: %.2e Msun
""" % (halo['uid'], halo['mass'].to('Msun'))
my_kwargs = {"label": label, "fontsize": 8,
"shape": "square", "color": color}
return my_kwargs
This function is then provided with the *node_function* keyword.
.. code-block:: python
>>> p = ytree.TreePlot(tree, dot_kwargs={'rankdir': "BT"},
... node_function=my_node)
>>> p.save('tree_custom_node.png')
.. image:: _images/tree_custom_node.png
Customizing Edge Appearance
^^^^^^^^^^^^^^^^^^^^^^^^^^^
The edges of the plot are the lines connecting each of the nodes. Similar to
the nodes, their appearance can be customized by providing a function that
returns a dictionary of keywords that will be used to create the ``pydot``
edge. This should accept two
:class:`~ytree.data_structures.tree_node.TreeNode` arguments representing
the ancestor and descendent halos being connected by the edge. The example
below colors the edges blue when the descendent is less massive than its
ancestor and green when the descendent is more than 10 times more massive
than its ancestor.
.. code-block:: python
def my_edge(ancestor, descendent):
if descendent['mass'] < ancestor['mass']:
color = 'blue'
elif descendent['mass'] / ancestor['mass'] > 10:
color = 'green'
else:
color = 'black'
my_kwargs = {"color": color, "penwidth": 5}
return my_kwargs
This function is then provided with the *edge_function* keyword.
.. code-block:: python
>>> p = ytree.TreePlot(tree, dot_kwargs={'rankdir': "BT"},
... node_function=my_node,
... edge_function=my_edge)
>>> p.save('tree_custom_edge.png')
.. image:: _images/tree_custom_edge.png
Supported Output Formats
^^^^^^^^^^^^^^^^^^^^^^^^
Plots can be saved to any format supported by ``graphviz`` by giving a
filename with the appropriate extension. See
`here <https://www.graphviz.org/doc/info/output.html>`__ for a list of
currently supported formats.
| ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/doc/source/Plotting.rst | Plotting.rst |
.. _fields:
Fields in ytree
===============
``ytree`` supports multiple types of fields, each representing numerical
values associated with each halo in the
:class:`~ytree.data_structures.arbor.Arbor`. These include the
:ref:`native fields <native-fields>` stored on disk, :ref:`alias fields
<alias-fields>`, :ref:`derived fields <derived-fields>`, and
:ref:`analysis fields <analysis-fields>`.
The Field Info Container
------------------------
Each :class:`~ytree.data_structures.arbor.Arbor` contains a dictionary,
called :func:`~ytree.data_structures.arbor.Arbor.field_info`,
with relevant information for each available field. This information
can include the units, type of field, any dependencies or aliases, and
things relevant to reading the data from disk.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("tree_0_0_0.dat")
>>> print (a.field_info["Rvir"])
{'description': 'Halo radius (kpc/h comoving).', 'units': 'kpc/h ', 'column': 11,
'aliases': ['virial_radius']}
>>> print (a.field_info["mass"])
{'type': 'alias', 'units': 'Msun', 'dependencies': ['Mvir']}
.. _native-fields:
Fields on Disk
--------------
Every field stored in the dataset's files should be available within
the :class:`~ytree.data_structures.arbor.Arbor`. The ``field_list``
contains a list of all fields on disk
with their native names.
.. code-block:: python
>>> print (a.field_list)
['scale', 'id', 'desc_scale', 'desc_id', 'num_prog', ...]
.. _alias-fields:
Alias Fields
------------
Because the various dataset formats use different naming conventions for
similar fields, ``ytree`` allows fields to be referred to by aliases. This
allows for a universal set of names for the most common fields. Many are
added by default, including "mass", "virial_radius", "position_<xyz>",
and "velocity_<xyz>". The list of available alias and derived fields
can be found in the ``derived_field_list``.
.. code-block:: python
>>> print (a.derived_field_list)
['uid', 'desc_uid', 'scale_factor', 'mass', 'virial_mass', ...]
Additional aliases can be added with
:func:`~ytree.data_structures.arbor.Arbor.add_alias_field`.
.. code-block:: python
>>> a.add_alias_field("amount_of_stuff", "mass", units="kg")
>>> print (a["amount_of_stuff"])
[ 1.30720461e+45, 1.05085632e+45, 1.03025691e+45, ...
1.72691772e+42, 1.72691772e+42, 1.72691772e+42]) kg
.. _derived-fields:
Derived Fields
--------------
Derived fields are functions of existing fields, including other
derived and alias fields. New derived fields are created by
providing a defining function and calling
:func:`~ytree.data_structures.arbor.Arbor.add_derived_field`.
.. code-block:: python
>>> def potential_field(field, data):
... # data.arbor points to the parent Arbor
... return data["mass"] / data["virial_radius"]
...
>>> a.add_derived_field("potential", potential_field, units="Msun/Mpc")
[ 2.88624262e+14 2.49542426e+14 2.46280488e+14, ...
3.47503685e+12 3.47503685e+12 3.47503685e+12] Msun/Mpc
Field functions should take two arguments. The first is a dictionary
that will contain basic information about the field, such as its name.
The second argument represents the data container for which the field
will be defined. It can be used to access field data for any other
available field. This argument will also have access to the parent
:class:`~ytree.data_structures.arbor.Arbor` as ``data.arbor``.
.. _vector-fields:
Vector Fields
-------------
For fields that have x, y, and z components, such as position, velocity,
and angular momentum, a single field can be queried to return an array
with all the components. For example, for fields named "position_x",
"position_y", and "position_z", the field "position" will return the
full vector.
.. code-block:: python
>>> print (a["position"])
[[0.0440018, 0.0672202, 0.9569643],
[0.7383264, 0.1961563, 0.0238852],
[0.7042797, 0.6165487, 0.500576 ],
...
[0.1822363, 0.1324423, 0.1722414],
[0.8649974, 0.4718005, 0.7349876]]) unitary
A list of defined vector fields can be seen by doing:
.. code-block:: python
>>> print (a.field_info.vector_fields)
('position', 'velocity', 'angular_momentum')
For all vector fields, a "_magnitude" field also exists, defined as the
quadrature sum of the components.
.. code-block:: python
>>> print (a["velocity_magnitude"])
[ 488.26936644 121.97143067 146.81450507, ...
200.74057711 166.13782652 529.7336846 ] km/s
Only specifically registered fields will be available as vector fields.
For example, saved :ref:`analysis-fields` with x,y,z components will
not automatically be available. However, vector fields can be created
with the :func:`~ytree.data_structures.arbor.Arbor.add_vector_field`
function.
.. code-block:: python
>>> a.add_vector_field("thing")
The above example assumes that fields named "thing_x", "thing_y",
and "thing_z" already exist.
.. _analysis-fields:
Analysis Fields
---------------
Analysis fields provide a means for saving the results of complicated
analysis for any halo in the :class:`~ytree.data_structures.arbor.Arbor`.
This would be operations beyond derived fields, for example, things that
might require loading the original simulation snapshots. New analysis
fields are created with
:func:`~ytree.data_structures.arbor.Arbor.add_analysis_field` and are
initialized to zero.
.. code-block:: python
>>> a.add_analysis_field("saucer_sections", units="m**2")
>>> my_tree = a[0]
>>> print (my_tree["tree", "saucer_sections"])
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0.,] m**2
>>> import numpy as np
>>> for halo in my_tree["tree"]:
... halo["saucer_sections"] = np.random.random() # complicated analysis
...
>>> print (my_tree["tree", "saucer_sections"])
[ 0.33919263 0.79557815 0.38264336 0.53073945 0.09634924 0.6035886, ...
0.9506636 0.9094426 0.85436984 0.66779632 0.58816873] m**2
Analysis fields will be saved when the
:class:`~ytree.data_structures.tree_node.TreeNode` objects that have been
analyzed are saved with :func:`~ytree.data_structures.arbor.Arbor.save_arbor`
or :func:`~ytree.data_structures.tree_node.TreeNode.save_tree`.
.. code-block:: python
>>> my_trees = list(a[:]) # all trees
>>> for my_tree in my_trees:
... # do analysis...
>>> a.save_arbor(trees=my_trees)
Note that we do ``my_trees = list(a[:])`` and not just ``my_trees =
a[:]``. This is because ``a[:]`` is a generator that will return a new
set of trees each time. The newly generated trees will not retain
changes made to any analysis fields. Thus, we must use ``list(a[:])``
to explicitly store a list of trees.
Re-saving Analysis Fields
^^^^^^^^^^^^^^^^^^^^^^^^^
All analysis fields are saved to sidecar files with the "-analysis" keyword
appended to them. They can be altered and the arbor re-saved as many times
as you like. In the very specific case of re-saving all trees and not
providing a new filename or custom list of fields (as in the example above),
analysis fields will be saved in place (i.e., over-writing the "-analysis"
files). The conventional on-disk fields will not be re-saved as they cannot
be altered.
| ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/doc/source/Fields.rst | Fields.rst |
.. _loading:
Loading Data
============
Below are instructions for loading all supported datasets. All examples
use the freely available :ref:`sample-data`.
.. _load-ahf:
Amiga Halo Finder
-----------------
The `Amiga Halo Finder <http://popia.ft.uam.es/AHF/Download.html>`__ format
stores data in a series of files, with one each per snapshot. Parameters
are stored in ".parameters" and ".log" files, halo information in
".AHF_halos" files, and descendent/ancestor links are stored in ".AHF_mtree"
files. Make sure to keep all of these together. To load, provide the name
of the first ".parameter" file.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("ahf_halos/snap_N64L16_000.parameter",
... hubble_constant=0.7)
.. note:: Four important notes about loading AHF data:
1. The dimensionless Hubble parameter is not provided in AHF
outputs. This should be supplied by hand using the
``hubble_constant`` keyword. The default value is 1.0.
2. If the ".log" file is named in a unconventional way or cannot
be found for some reason, its path can be specified with the
``log_filename`` keyword argument. If no log file exists,
values for ``omega_matter``, ``omega_lambda``, and ``box_size``
(in units of Mpc/h) can be provided with keyword arguments
named thusly.
3. There will be no ".AHF_mtree" file for index 0 as the
".AHF_mtree" files store links between files N-1 and N.
4. ``ytree`` is able to load data where the graph has been
calculated instead of the tree. However, even in this case,
only the tree is preserved in ``ytree``. See the `Amiga Halo
Finder Documentation
<http://popia.ft.uam.es/AHF/Documentation.html>`_
for a discussion of the difference between graphs and trees.
.. _load-ctrees:
Consistent-Trees
----------------
The `consistent-trees <https://bitbucket.org/pbehroozi/consistent-trees>`__
format consists of a set of files called "locations.dat", "forests.list",
at least one file named something like "tree_0_0_0.dat". For large
simulations, there may be a number of these "tree_*.dat" files. After
running Rockstar and consistent-trees, these will most likely be located in
the "rockstar_halos/trees" directory. The full data set can be loaded by
providing the path to the *locations.dat* file.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("tiny_ctrees/locations.dat")
Alternatively, data from a single tree file can be loaded by providing the
path to that file.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("consistent_trees/tree_0_0_0.dat")
Consistent-Trees hlist Files
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
While running consistent-trees, a series of files will be created in the
"rockstar_halos/hlists" directory with the naming convention,
"hlist_<scale-factor>.list". These are the catalogs that will be combined
to make the final output files. However, these files contain roughly 30
additional fields that are not included in the final output. Merger trees
can be loaded by providing the path to the first of these files.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("ctrees_hlists/hlists/hlist_0.12521.list")
.. note:: Note, loading trees with this method will be slower than using
the standard consistent-trees output file as ``ytree`` will have to
assemble each tree across multiple files. This method is not
recommended unless the additional fields are necessary.
.. _load-ctrees-hdf5:
Consistent-Trees-HDF5
---------------------
`Consistent-Trees-HDF5 <https://github.com/uchuuproject/uchuutools>`__
is a variant of the consistent-trees format built on HDF5. It is used by
the `Skies & Universe <http://www.skiesanduniverses.org/>`_ project.
This format allows for access by either `forests` or `trees` as per the
definitions above. The data can be stored as either a struct of arrays
or an array of structs. Both layouts are supported, but ``ytree`` is
currently optimized for the struct of arrays layout. Field access with
struct of arrays will be 1 to 2 orders of magnitude faster than with
array of structs.
Datasets from this format consist of a series of HDF5 files with the
naming convention, `forest.h5`, `forest_0.5`, ..., `forest_N.h5`.
The numbered files contain the actual data while the `forest.h5` file
contains virtual datasets that point to the data files. To load all
the data, provide the path to the virtual dataset file:
.. code-block:: python
>>> import ytree
>>> a = ytree.load("consistent_trees_hdf5/soa/forest.h5")
To load a subset of the full dataset, provide a single data file or
a list/tuple of files.
.. code-block:: python
>>> import ytree
>>> # single file
>>> a = ytree.load("consistent_trees_hdf5/soa/forest_0.h5")
>>> # multiple data files (sample data only has one)
>>> a = ytree.load(["forest_0.h5", "forest_1.h5"])
Access by Forest
^^^^^^^^^^^^^^^^
By default, ``ytree`` will load consistent-trees-hdf5 datasets to
provide access to each tree, such that ``a[N]`` will return the Nth
tree in the dataset and ``a[N]["tree"]`` will return all halos in
that tree. However, by providing the ``access="forest"`` keyword to
:func:`~ytree.data_structures.load.load`, data will be loaded
according to the forest it belongs to.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("consistent_trees_hdf5/soa/forest.h5",
... access="forest")
In this mode, ``a[N]`` will return the Nth forest and
``a[N]["forest"]`` will return all halos in that forest. In
forest access mode, the "root" of the forest, i.e., the
:class:`~ytree.data_structures.tree_node.TreeNode` object returned
by doing ``a[N]`` will be the root of one of the trees in that
forest. See :ref:`forest-access` for how to locate all individual
trees in a forest.
.. _load-lhalotree:
LHaloTree
---------
The `LHaloTree <http://adsabs.harvard.edu/abs/2005Natur.435..629S>`__
format is typically one or more files with a naming convention like
"trees_063.0" that contain the trees themselves and a single file
with a suffix ".a_list" that contains a list of the scale factors
at the time of each simulation snapshot.
.. note:: The LHaloTree format loads halos by forest. There is no need
to provide the ``access="forest"`` keyword here.
In addition to the LHaloTree files, ``ytree`` also requires additional
information about the simulation from a parameter file (in
`Gadget <http://wwwmpa.mpa-garching.mpg.de/gadget/>`_ format). At
minimum, the parameter file should contain the cosmological parameters
``HubbleParam, Omega0, OmegaLambda, BoxSize, PeriodicBoundariesOn,``
and ``ComovingIntegrationOn``, and the unit parameters
``UnitVelocity_in_cm_per_s, UnitLength_in_cm,`` and ``UnitMass_in_g``.
If not specified explicitly (see below), a file with the extension
".param" will be searched for in the directory containing the
LHaloTree files.
If all of the required files are in the same directory, an LHaloTree
catalog can be loaded from the path to one of the tree files.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("lhalotree/trees_063.0")
Both the scale factor and parameter files can be specified explicitly
through keyword arguments if they do not match the expected pattern
or are located in a different directory than the tree files.
.. code-block:: python
>>> a = ytree.load("lhalotree/trees_063.0",
... parameter_file="lhalotree/param.txt",
... scale_factor_file="lhalotree/a_list.txt")
The scale factors and/or parameters themselves can also be passed
explicitly from python.
.. code-block:: python
>>> import numpy as np
>>> parameters = dict(HubbleParam=0.7, Omega0=0.3, OmegaLambda=0.7,
... BoxSize=62500, PeriodicBoundariesOn=1, ComovingIntegrationOn=1,
... UnitVelocity_in_cm_per_s=100000, UnitLength_in_cm=3.08568e21,
... UnitMass_in_g=1.989e+43)
>>> scale_factors = [ 0.0078125, 0.012346 , 0.019608 , 0.032258 , 0.047811 ,
... 0.051965 , 0.056419 , 0.061188 , 0.066287 , 0.071732 ,
... 0.07754 , 0.083725 , 0.090306 , 0.097296 , 0.104713 ,
... 0.112572 , 0.120887 , 0.129675 , 0.13895 , 0.148724 ,
... 0.159012 , 0.169824 , 0.181174 , 0.19307 , 0.205521 ,
... 0.218536 , 0.232121 , 0.24628 , 0.261016 , 0.27633 ,
... 0.292223 , 0.308691 , 0.32573 , 0.343332 , 0.361489 ,
... 0.380189 , 0.399419 , 0.419161 , 0.439397 , 0.460105 ,
... 0.481261 , 0.502839 , 0.524807 , 0.547136 , 0.569789 ,
... 0.59273 , 0.615919 , 0.639314 , 0.66287 , 0.686541 ,
... 0.710278 , 0.734031 , 0.757746 , 0.781371 , 0.804849 ,
... 0.828124 , 0.851138 , 0.873833 , 0.896151 , 0.918031 ,
... 0.939414 , 0.960243 , 0.980457 , 1. ]
>>> a = ytree.load("lhalotree/trees_063.0",
... parameters=parameters,
... scale_factors=scale_factors)
.. _load-lhalotree-hdf5:
LHaloTree-HDF5
--------------
This is the same algorithm as :ref:`load-lhalotree`, except with data
saved in HDF5 files instead of unformatted binary. LHaloTree-HDF5 is
one of the formats used by the
`Illustris-TNG project <https://www.tng-project.org/>`__ and is
described in detail
`here <https://www.tng-project.org/data/docs/specifications/#sec4b>`__.
Like :ref:`load-lhalotree`, this format supports :ref:`accessing trees
by forest <forest-access>`. The LHaloTree-HDF5 format stores trees in
multiple HDF5 files contained within a single directory. Each tree is
fully contained within a single file, so loading is possible even when
only a subset of all files is present. To load, provide the path to
one file.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("TNG50-4-Dark/trees_sf1_099.0.hdf5")
The files do not contain information on the box size and cosmological
parameters of the simulation, but they can be provided by hand, with
the box size assumed to be in units of comoving Mpc/h.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("TNG50-4-Dark/trees_sf1_099.0.hdf5",
... box_size=35, hubble_constant=0.6774,
... omega_matter=0.3089, omega_lambda=0.6911)
The LHaloTree-HDF5 format contains multiple definitions of halo mass
(see `here <https://www.tng-project.org/data/docs/specifications/#sec4b>`__),
and as such, the field alias "mass" is not defined by default. However,
the :ref:`alias can be created <alias-fields>` if one is preferable. This
is also necessary to facilitate :ref:`progenitor-access`.
.. code-block:: python
>>> a.add_alias_field("mass", "Group_M_TopHat200", units="Msun")
.. _load-moria:
MORIA
-----
`MORIA <https://bdiemer.bitbucket.io/sparta/analysis_moria.html>`__ is a
merger tree extension of the
`SPARTA <https://bdiemer.bitbucket.io/sparta/index.html>`__ code
(`Diemer 2017 <https://ui.adsabs.harvard.edu/abs/2017ApJS..231....5D/>`__;
`Diemer 2020a <https://ui.adsabs.harvard.edu/abs/2020ApJS..251...17D/>`__).
An output from MORIA is a single HDF5 file, whose path should be provided
for loading.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("moria/moria_tree_testsim050.hdf5")
Merger trees in MORIA are organized by :ref:`forest <forest-access>`, so
printing ``a.size`` (following the example above) will give the number of
forests, not the number of trees. MORIA outputs contain multiple definitions
of halo mass (see `here
<https://bdiemer.bitbucket.io/sparta/analysis_moria_output.html#complete-list-of-catalog-tree-fields-in-erebos-catalogs>`__),
and as such, the field alias "mass" is not defined by default. However,
the :ref:`alias can be created <alias-fields>` if one is preferable. This
is also necessary to facilitate :ref:`progenitor-access`.
.. code-block:: python
>>> a.add_alias_field("mass", "Mpeak", units="Msun")
On rare occasions, a halo will be missing from the output even though
another halo claims it as its descendent. This is usually because the
halo has dropped below the minimum mass to be included. In these cases,
MORIA will reassign the halo's descendent using the ``descendant_index``
field (see discussion in `here
<https://bdiemer.bitbucket.io/sparta/analysis_moria_output.html>`__).
If ``ytree`` encounters such a situation, a message like the one below
will be printed.
.. code-block:: python
>>> t = a[85]
>>> print (t["tree", "Mpeak"])
ytree: [INFO ] 2021-05-04 15:29:19,723 Reassigning descendent of halo 374749 from 398837 to 398836.
[1.458e+13 1.422e+13 1.363e+13 1.325e+13 1.295e+13 1.258e+13 1.212e+13 ...
1.309e+11 1.178e+11 1.178e+11 1.080e+11 9.596e+10 8.397e+10] Msun/h
.. _load-rockstar:
Rockstar Catalogs
-----------------
`Rockstar <https://bitbucket.org/gfcstanford/rockstar>`__
catalogs with the naming convention "out_*.list" will contain
information on the descendent ID of each halo and can be loaded
independently of consistent-trees. This can be useful when your
simulation has very few halos, such as in a zoom-in simulation. To
load in this format, simply provide the path to one of these files.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("rockstar/rockstar_halos/out_0.list")
.. _load-treefarm:
TreeFarm
--------
Merger trees created with `treefarm <https://treefarm.readthedocs.io/>`__
can be loaded in by providing the path to one of the catalogs created
during the calculation.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("tree_farm/tree_farm_descendents/fof_subhalo_tab_000.0.h5")
.. _load-treefrog:
TreeFrog
--------
`TreeFrog <https://github.com/pelahi/TreeFrog>`__ generates merger trees
primarily for `VELOCIraptor <https://github.com/pelahi/VELOCIraptor-STF>`__
halo catalogs. The TreeFrog format consists of a series of HDF5 files.
One file contains meta-data for the entire dataset. The other files contain
the tree data, split into HDF5 groups corresponding to the original halo
catalogs. To load, provide the path to the "foreststats" file, i.e., the
one ending in ".hdf5".
.. code-block:: python
>>> import ytree
>>> a = ytree.load("treefrog/VELOCIraptor.tree.t4.0-131.walkabletree.sage.forestID.foreststats.hdf5")
Merger trees in TreeFrog are organized by :ref:`forest <forest-access>`, so
printing ``a.size`` (following the example above) will give the number of
forests. Note, however, the id of the root halo for any given forest is not
the same as the forest id.
.. code-block:: python
>>> my_tree = a[0]
>>> print (my_tree["uid"])
131000000000001
>>> print (my_tree["ForestID"])
104000000011727
TreeFrog outputs contain multiple definitions of halo mass, and as such, the field
alias "mass" is not defined by default. However, the :ref:`alias can be created
<alias-fields>` if one is preferable. This is also necessary to facilitate
:ref:`progenitor-access`.
.. code-block:: python
>>> a.add_alias_field("mass", "Mass_200crit", units="Msun")
.. _load-ytree:
Saved Arbors (ytree format)
---------------------------
Once merger tree data has been loaded, it can be saved to a
universal format using :func:`~ytree.data_structures.arbor.Arbor.save_arbor` or
:func:`~ytree.data_structures.tree_node.TreeNode.save_tree`. These can be loaded
by providing the path to the primary HDF5 file.
.. code-block:: python
>>> import ytree
>>> a = ytree.load("arbor/arbor.h5")
See :ref:`saving-trees` for more information on saving arbors and trees.
| ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/doc/source/Loading.rst | Loading.rst |
Welcome to ytree.
=================
``ytree`` is a tool for working with merger tree data from multiple
sources. ``ytree`` is an extension of the `yt
<https://yt-project.org/>`_ analysis toolkit and provides a similar
interface for merger tree data that includes universal field names,
derived fields, symbolic units, parallel functionality, and a
framework for performing complex analysis. ``ytree`` is able to load
in merger tree from the following formats:
- :ref:`load-ahf`
- :ref:`load-ctrees`
- :ref:`load-ctrees-hdf5`
- :ref:`load-lhalotree`
- :ref:`load-lhalotree-hdf5`
- :ref:`load-moria`
- :ref:`load-rockstar`
- :ref:`load-treefarm`
- :ref:`load-treefrog`
See :ref:`loading` for instructions specific to each format.
All formats can be :ref:`resaved with a universal format <saving-trees>` that
can be :ref:`reloaded with ytree <load-ytree>`. Individual trees for single
halos can also be saved.
I want to make merger trees!
============================
If you have halo catalog data that can be loaded by
`yt <https://yt-project.org/>`_, then you can use the
`treefarm <https://treefarm.readthedocs.io/>`_ package to create
merger trees. `treefarm <https://treefarm.readthedocs.io/>`_ was
once a part of ``ytree``, but is now its own thing.
Table of Contents
=================
.. toctree::
:maxdepth: 2
Installation.rst
Data.rst
Frames.rst
Arbor.rst
Fields.rst
Plotting.rst
Parallelism.rst
Analysis.rst
Examples.rst
Conduct.rst
Contributing.rst
Developing.rst
Help.rst
Citing.rst
reference.rst
.. include:: ../../CITATION.rst
Search
======
* :ref:`search`
| ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/doc/source/index.rst | index.rst |
.. _installation:
Installation
============
``ytree``'s main dependency is `yt <http://yt-project.org/>`_. Once you
have installed ``yt`` following the instructions `here
<http://yt-project.org/#getyt>`__, ``ytree`` can be installed using pip.
.. code-block:: bash
$ pip install ytree
If you'd like to install the development version, the repository can
be found at `<https://github.com/ytree-project/ytree>`__. This can be
installed by doing:
.. code-block:: bash
$ git clone https://github.com/ytree-project/ytree
$ cd ytree
$ pip install -e .
What version do I have?
=======================
To see what version of ``ytree`` you are using, do the following:
.. code-block:: python
>>> import ytree
>>> print (ytree.__version__)
| ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/doc/source/Installation.rst | Installation.rst |
.. _changelog:
ChangeLog
=========
This is a log of changes to ``ytree`` over its release history.
Contributors
------------
The `CREDITS file
<https://github.com/ytree-project/ytree/blob/main/CREDITS>`__
contains the most up-to-date list of everyone who has contributed to the
``ytree`` source code.
Version 3.1.1
-------------
Release date: *February 3, 2022*
Bugfixes
^^^^^^^^
* Allow parallel_trees to work with non-root trees.
(`PR #123 <https://github.com/ytree-project/ytree/pull/123>`__)
* Use smarter regexes to get AHF naming scheme.
(`PR #118 <https://github.com/ytree-project/ytree/pull/118>`__)
* Add return value to comply with yt.
(`PR #121 <https://github.com/ytree-project/ytree/pull/121>`__)
Infrastructure Updates
^^^^^^^^^^^^^^^^^^^^^^
* Implement _apply_units method.
(`PR #122 <https://github.com/ytree-project/ytree/pull/122>`__)
* Enable parallelism on circleci.
(`PR #120 <https://github.com/ytree-project/ytree/pull/120>`__)
* Create pypi upload action.
(`PR #124 <https://github.com/ytree-project/ytree/pull/124>`__)
Version 3.1
-----------
Release date: *August 30, 2021*
New Featues
^^^^^^^^^^^
* Add AnalysisPipeline
(`PR #113 <https://github.com/ytree-project/ytree/pull/113>`__)
* Add Parallel Iterators
(`PR #112 <https://github.com/ytree-project/ytree/pull/112>`__)
Version 3.0
-----------
Release date: *August 3, 2021*
New Featues
^^^^^^^^^^^
* Halo selection and generation with yt data objects
(`PR #82 <https://github.com/ytree-project/ytree/pull/82>`__)
* Add frontends for consistent-trees hlist and locations.dat files
(`PR #48 <https://github.com/ytree-project/ytree/pull/48>`__)
* Add consistent-trees HDF5 frontend
(`PR #53 <https://github.com/ytree-project/ytree/pull/53>`__)
* Add LHaloTree_hdf5 frontend
(`PR #81 <https://github.com/ytree-project/ytree/pull/81>`__)
* Add TreeFrog frontend
(PR `#103 <https://github.com/ytree-project/ytree/pull/103>`__,
`#95 <https://github.com/ytree-project/ytree/pull/95>`__,
`#88 <https://github.com/ytree-project/ytree/pull/88>`__)
* Add Moria frontend
(`PR #84 <https://github.com/ytree-project/ytree/pull/84>`__)
* Add get_node and get_leaf_nodes functions
(`PR #80 <https://github.com/ytree-project/ytree/pull/80>`__)
* Add get_root_nodes function
(`PR #91 <https://github.com/ytree-project/ytree/pull/91>`__)
* Add add_vector_field function
(`PR #71 <https://github.com/ytree-project/ytree/pull/71>`__)
* Add plot customization
(`PR #49 <https://github.com/ytree-project/ytree/pull/49>`__)
Enhancements
^^^^^^^^^^^^
* All functions returning TreeNodes now return generators for a
significant speed and memory usage improvement.
(PR `#104 <https://github.com/ytree-project/ytree/pull/104>`__,
`#64 <https://github.com/ytree-project/ytree/pull/64>`__,
`#61 <https://github.com/ytree-project/ytree/pull/61>`__)
* Speed and usability improvements to select_halos function
(PR `#83 <https://github.com/ytree-project/ytree/pull/83>`__,
`#72 <https://github.com/ytree-project/ytree/pull/72>`__)
* Add parallel analysis docs
(`PR #106 <https://github.com/ytree-project/ytree/pull/106>`__)
* Make field_data an public facing attribute.
(`PR #105 <https://github.com/ytree-project/ytree/pull/105>`__)
* Improved sorting for node_io_loop in ctrees_group and ctrees_hdf5
(`PR #87 <https://github.com/ytree-project/ytree/pull/87>`__)
* Relax requirements on cosmological parameters and add load options
for AHF frontend
(`PR #76 <https://github.com/ytree-project/ytree/pull/76>`__)
* Speed and usability updates to save_arbor function
(PR `#68 <https://github.com/ytree-project/ytree/pull/68>`__,
`#58 <https://github.com/ytree-project/ytree/pull/58>`__)
* Various infrastructure updates for newer versions of Python and
dependencies
(PR `#92 <https://github.com/ytree-project/ytree/pull/92>`__,
`#78 <https://github.com/ytree-project/ytree/pull/78>`__,
`#75 <https://github.com/ytree-project/ytree/pull/75>`__,
`#60 <https://github.com/ytree-project/ytree/pull/60>`__,
`#54 <https://github.com/ytree-project/ytree/pull/54>`__,
`#45 <https://github.com/ytree-project/ytree/pull/45>`__)
* Update frontend development docs
(`PR #69 <https://github.com/ytree-project/ytree/pull/69>`__)
* CI updates
(PR `#101 <https://github.com/ytree-project/ytree/pull/101>`__,
`#96 <https://github.com/ytree-project/ytree/pull/96>`__,
`#94 <https://github.com/ytree-project/ytree/pull/94>`__,
`#93 <https://github.com/ytree-project/ytree/pull/93>`__,
`#86 <https://github.com/ytree-project/ytree/pull/86>`__,
`#79 <https://github.com/ytree-project/ytree/pull/79>`__,
`#74 <https://github.com/ytree-project/ytree/pull/74>`__,
`#73 <https://github.com/ytree-project/ytree/pull/73>`__)
`#63 <https://github.com/ytree-project/ytree/pull/63>`__,
`#55 <https://github.com/ytree-project/ytree/pull/55>`__,
`#51 <https://github.com/ytree-project/ytree/pull/51>`__,
`#50 <https://github.com/ytree-project/ytree/pull/50>`__,
`#43 <https://github.com/ytree-project/ytree/pull/43>`__,
`#42 <https://github.com/ytree-project/ytree/pull/42>`__)
* Remove support for ytree-1.x outputs
(`PR #62 <https://github.com/ytree-project/ytree/pull/62>`__)
* Drop support for python 3.5
(`PR #59 <https://github.com/ytree-project/ytree/pull/59>`__)
* Drop support for Python 2
(`PR #41 <https://github.com/ytree-project/ytree/pull/41>`__)
Bugfixes
^^^^^^^^
* Use file sizes of loaded arbor when only saving analysis fields.
(`PR #100 <https://github.com/ytree-project/ytree/pull/100>`__)
* Use regex for more robust filename check.
(PR `#77 <https://github.com/ytree-project/ytree/pull/77>`__,
`#47 <https://github.com/ytree-project/ytree/pull/47>`__)
* Fix issue with saving full arbor
(`PR #70 <https://github.com/ytree-project/ytree/pull/70>`__)
* Check if attr is bytes or string.
(`PR #57 <https://github.com/ytree-project/ytree/pull/57>`__)
* Fix arg in error message.
(`PR #56 <https://github.com/ytree-project/ytree/pull/56>`__)
* Account for empty ctrees files in data files list
(`PR #52 <https://github.com/ytree-project/ytree/pull/52>`__)
Version 2.3
-----------
Release date: *December 17, 2019*
This release marks the `acceptance of the ytree paper
<https://github.com/openjournals/joss-reviews/issues/1881>`__ in
`JOSS <https://joss.theoj.org/>`__.
This is the last release to support Python 2.
New Features
^^^^^^^^^^^^
* Add TreePlot for plotting and examples docs
(`PR #39 <https://github.com/ytree-project/ytree/pull/39>`__)
Enhancements
^^^^^^^^^^^^
* Add time field
(`PR #25 <https://github.com/ytree-project/ytree/pull/25>`__)
* Move treefarm module to separate package
(`PR #28 <https://github.com/ytree-project/ytree/pull/28>`__)
Version 2.2.1
-------------
Release date: *October 24, 2018*
Enhancements
^^^^^^^^^^^^
* Refactor of CatalogDataFile class
(`PR #21 <https://github.com/ytree-project/ytree/pull/21>`__)
* Simplify requirements file for docs build on readthedocs.io
(`PR #22 <https://github.com/ytree-project/ytree/pull/22>`__)
Bugfixes
^^^^^^^^
* Restore access to analysis fields for tree roots
(`PR #23 <https://github.com/ytree-project/ytree/pull/23>`__)
* fix field access on non-root nodes when tree is not setup
(`PR #20 <https://github.com/ytree-project/ytree/pull/20>`__)
* fix issue of uid and desc_uid fields being clobbered during
initial field access
(`PR #19 <https://github.com/ytree-project/ytree/pull/19>`__)
Version 2.2
-----------
Release date: *August 28, 2018*
New Features
^^^^^^^^^^^^
* add vector fields.
* add select_halos function.
Enhancements
^^^^^^^^^^^^
* significant refactor of field and i/o systems.
* upgrades to testing infrastructure.
Version 2.1.1
-------------
Release date: *April 23, 2018*
Bugfixes
^^^^^^^^
* update environment.yml to fix broken readthedocs build.
Version 2.1
-----------
Release date: *April 20, 2018*
New Features
^^^^^^^^^^^^
* add support for LHaloTree format.
* add support for Amiga Halo Finder format.
Version 2.0.2
-------------
Release date: *February 16, 2018*
Enhancements
^^^^^^^^^^^^
* significantly improved i/o for ytree frontend.
Version 2.0
-----------
Release date: *August 07, 2017*
This is significant overhaul of the ytree machinery.
New Features
^^^^^^^^^^^^
* tree building and field i/o now occur on-demand.
* support for yt-like derived fields that can be defined with simple
functions.
* support for yt-like alias fields allowing for universal
field naming conventions to simplify writing scripts for multiple
data formats.
* support for analysis fields which allow users to save the results
of expensive halo analysis to fields associated with each halo.
* all fields in consistent-trees and Rockstar now fully supported with
units.
* an optimized format for saving and reloading trees for fast field access.
Enhancements
^^^^^^^^^^^^
* significantly improved documentation including a guide to adding support
for new file formats.
Version 1.1
-----------
Release date: *January 12, 2017*
New Features
^^^^^^^^^^^^
* New, more yt-like field querying syntax for both arbors and tree
nodes.
Enhancements
^^^^^^^^^^^^
* Python3 now supported.
* More robust unit system with restoring of unit registries from stored
json.
* Added minimum radius to halo sphere selector.
* Replaced import of yt for specific imports of all required functions.
* Added ytree logger.
* Docs updated and API reference docs added.
Bugfixes
^^^^^^^^
* Allow non-root trees to be saved and reloaded.
* Fix bug allowing trees that end before the final output.
Version 1.0
-----------
Release date: *Sep 26, 2016*
The inaugural release of ytree!
| ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/doc/source/changelog.rst | changelog.rst |
.. _frames:
An Important Note on Comoving and Proper Units
==============================================
Users of ``yt`` are likely familiar with conversion from proper to comoving
reference frames by adding "cm" to a unit. For example, proper "Mpc"
becomes comoving with "Mpccm". This conversion relies on all the data
being associated with a single redshift. This is not possible here
because the dataset has values for multiple redshifts. To account for
this, the proper and comoving unit systems are set to be equal to each
other.
.. code-block:: python
>>> print (a.box_size)
100.0 Mpc/h
>>> print (a.box_size.to("Mpccm/h"))
100.0 Mpccm/h
Data should be assumed to be in the reference frame in which it
was saved. For length scales, this is typically the comoving frame.
When in doubt, the safest unit to use for lengths is "unitary", which
a system normalized to the box size.
.. code-block:: python
>>> print (a.box_size.to("unitary"))
1.0 unitary
| ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/doc/source/Frames.rst | Frames.rst |
Help
====
If you encounter problems, we want to help and there are lots
of places to get help. As an extension of `the yt project
<https://yt-project.org/>`_, we are members of the yt community.
There is a dedicated #ytree channel on the `yt project Slack
<https://yt-project.org/slack.html>`__ and questions can also
be posted to the `yt users mailing list
<https://mail.python.org/mailman3/lists/yt-users.python.org>`__.
Bugs and feature requests can also be posted on the `ytree issues
page <https://github.com/ytree-project/ytree/issues>`__.
See you out there!
| ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/doc/source/Help.rst | Help.rst |
.. _analysis:
Analyzing Merger Trees
======================
This section describes the preferred method for performing analysis
on merger trees that results in modification of the dataset (e.g., by
creating or altering :ref:`analysis-fields`) or writing additional
files. The end of this section, :ref:`parallel_analysis`, illustrates
an analysis workflow that will run in parallel.
When performing the same analysis on a large number of items, we often
think in terms of creating an "analysis pipeline", where a series of
discrete actions, including deciding whether to skip a given item, are
embedded within a loop over all the items to analyze. For merger
trees, this may look something like the following:
.. code-block:: python
import ytree
a = ytree.load(...)
trees = list(a[:])
for tree in trees:
for node in tree["forest"]:
# only analyze above some minimum mass
if node["mass"] < a.quan(1e11, "Msun"):
continue
# get simulation snapshot associated with this halo
snap_fn = get_filename_from_redshift(node["redshift"])
ds = yt.load(snap_fn)
# get sphere using halo's center and radius
center = node["position"].to("unitary")
radius = node["virial_radius"].to("unitary")
sp = ds.sphere((center, "unitary"), (radius, "unitary"))
# calculate gas mass and save to field
node["gas_mass"] = sp.quantities.total_quantity(("gas", "mass"))
# make a projection and save an image
p = yt.ProjectionPlot(ds, "x", ("gas", "density"),
data_source=sp, center=sp.center,
width=2*sp.width)
p.save("my_analysis/projections/")
There are a few disadvantages of this approach. The inner loop is very
long. It can be difficult to understand the full set of actions,
especially if you weren't the one who wrote it. If there is a section
you no longer want to do, a whole block of code needs to be commented
out or removed, and it may be tricky to tell if doing that will break
something else. Putting the operations into functions will make this
simpler, but it can still make for a large code block in the inner
loop. As well, if the structure of the loops over trees or nodes is
more complicated than the above, there is potential for the code to be
non-trivial to digest.
.. _analysis_pipeline:
The AnalysisPipeline
--------------------
The :class:`~ytree.analysis.analysis_pipeline.AnalysisPipeline` allows
you to design the analysis workflow in advance and then use it to
process a tree or node with a single function call. Skipping straight
to the end, the loop from above will take the form:
.. code-block:: python
for tree in trees:
for node in tree["forest"]:
ap.process_target(node)
In the above example, "ap" is some
:class:`~ytree.analysis.analysis_pipeline.AnalysisPipeline` object
that we have defined earlier. We will now take a closer look at how to
design a workflow using this method.
Creating an AnalysisPipeline
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
An :class:`~ytree.analysis.analysis_pipeline.AnalysisPipeline` is
instantiated with no arguments. Only an optional output directory
inside which new files will be written can be specified with the
``output_dir`` keyword.
.. code-block:: python
import ytree
ap = ytree.AnalysisPipeline(output_dir="my_analysis")
The output directory will be created automatically if it does not
already exist.
Creating Pipeline Operations
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
An analysis pipeline is assembled by creating functions that accept a
single :class:`~ytree.data_structures.tree_node.TreeNode` as an
argument.
.. code-block:: python
def say_hello(node):
print (f"This is node {node}! I will now be analyzed.")
This function can now be added to an existing pipeline with the
:func:`~ytree.analysis.analysis_pipeline.AnalysisPipeline.add_operation`
function.
.. code-block:: python
ap.add_operation(say_hello)
Now, when the
:func:`~ytree.analysis.analysis_pipeline.AnalysisPipeline.process_target`
function is called with a
:class:`~ytree.data_structures.tree_node.TreeNode` object, the
``say_hello`` function will be called with that
:class:`~ytree.data_structures.tree_node.TreeNode`. Any additional
calls to
:func:`~ytree.analysis.analysis_pipeline.AnalysisPipeline.add_operation`
will result in those functions also being called with that
:class:`~ytree.data_structures.tree_node.TreeNode` in the same order.
Adding Extra Function Arguments
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Functions can take additional arguments and keyword arguments as
well.
.. code-block:: python
def print_field_value(node, field, units=None):
val = node[field]
if units is not None:
val.convert_to_units(units)
print (f"Value of {field} for node {node} is {val}.")
The additional arguments and keyword arguments are then provided when
calling
:func:`~ytree.analysis.analysis_pipeline.AnalysisPipeline.add_operation`.
.. code-block:: python
ap.add_operation(print_field_value, "mass")
ap.add_operation(print_field_value, "virial_radius", units="kpc/h")
Organizing File Output by Operation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
In the same way that the
:class:`~ytree.analysis.analysis_pipeline.AnalysisPipeline` object
accepts an ``output_dir`` keyword, analysis functions can also accept
an ``output_dir`` keyword.
.. code-block:: python
def save_something(node, output_dir=None):
# make an HDF5 file named by the unique node ID
filename = f"node_{node.uid}.h5"
if output_dir is not None:
filename = os.path.join(output_dir, filename)
# do some stuff...
# meanwhile, back in the pipeline...
ap.add_operation(save_something, output_dir="images")
This ``output_dir`` keyword will be intercepted by the
:class:`~ytree.analysis.analysis_pipeline.AnalysisPipeline` object to
ensure that the directory gets created if it does not already
exist. Additionally, if an ``output_dir`` keyword was given when the
:class:`~ytree.analysis.analysis_pipeline.AnalysisPipeline` was
created, as in the example above, the directory associated with the
function will be appended to that. Following the examples here, the
resulting directory would be "my_analysis/images", and the code above
will correctly save to that location.
Using a Function as a Filter
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Making an analysis function return ``True`` or ``False`` allows it to
act as a filter. If a function returns ``False``, then any
additional operations defined in the pipeline will not be
performed. For example, we might create a mass filter like this:
.. code-block:: python
def minimum_mass(node, value):
return node["mass"] >= value
# later, in the pipeline
ap.add_operation(minimum_mass, a.quan(1e11, "Msun"))
Modifying a Node
^^^^^^^^^^^^^^^^
There may be occasions where you want to pass local variables or
objects around from one function to the next. The easiest way to do
this is by attaching them to the
:class:`~ytree.data_structures.tree_node.TreeNode` object itself as an
attribute. For example, say we have a function that returns a
simulation snapshot loaded with ``yt`` as a function of redshift. We
might do something like the the following to then pass it to another
function which creates a ``yt`` sphere.
.. code-block:: python
def get_yt_dataset(node):
# assume you have something like this
filename = get_filename_from_redshift(node["redshift"])
# attach it to the node for later use
node.ds = yt.load(filename)
def get_yt_sphere(node):
# this works if get_yt_dataset has been called first
ds = node.ds
center = node["position"].to("unitary")
radius = node["virial_radius"].to("unitary")
node.sphere = ds.sphere((center, "unitary"), (radius, "unitary"))
Then, we can add these to the pipeline such that a later function can
use the sphere.
.. code-block:: python
ap.add_operation(get_yt_dataset)
ap.add_operation(get_yt_sphere)
To clean things up, we can make a function to remove attributes and
add it to the end of the pipeline.
.. code-block:: python
def delete_attributes(node, attributes):
for attr in attributes:
delattr(node, attr)
# later, in the pipeline
ap.add_operation(delete_attributes, ["ds", "sphere"])
Running the Pipeline
^^^^^^^^^^^^^^^^^^^^
Once the pipeline has been defined through calls to
:func:`~ytree.analysis.analysis_pipeline.AnalysisPipeline.add_operation`,
it is now only a matter of looping over the nodes we want to analyze
and calling
:func:`~ytree.analysis.analysis_pipeline.AnalysisPipeline.process_target`
with them.
.. code-block:: python
for tree in trees:
for node in tree["forest"]:
ap.process_target(node)
Depending on what you want to do, you may want to call
:func:`~ytree.analysis.analysis_pipeline.AnalysisPipeline.process_target`
with an entire tree and skip the inner loop. After all, a tree in this
context is just another
:class:`~ytree.data_structures.tree_node.TreeNode` object, only one
that has no descendent.
Creating a Analysis Recipe
^^^^^^^^^^^^^^^^^^^^^^^^^^
Through the previous examples, we have designed a workflow by defining
functions and adding them to our pipeline in the order we want them to
be called. Has it resulted in fewer lines of code? No. But it has
allowed us to construct a workflow out of a series of reusable parts,
so the creation of future pipelines will certainly involve fewer lines
of code. It is also possible to define a more complex series of
operations as a "recipe" that can be added in one go to the pipeline
using the
:func:`~ytree.analysis.analysis_pipeline.AnalysisPipeline.add_recipe`
function. A recipe should be a function that, minimally, accepts an
:class:`~ytree.analysis.analysis_pipeline.AnalysisPipeline` object as
the first argument, but can also accept more. Below, we will define a
recipe for calculating the gas mass for a halo. For our purposes,
assume the functions we created earlier exist here.
.. code-block:: python
def calculate_gas_mass(node):
sphere = node.sphere
node["gas_mass"] = sphere.quantities.total_quantity(("gas", "mass"))
def gas_mass_recipe(pipeline):
pipeline.add_operation(get_yt_dataset)
pipeline.add_operation(get_yt_sphere)
pipeline.add_operation(calculate_gas_mass)
pipeline.add_operation(delete_attributes, ["ds", "sphere"])
Now, our entire analysis pipeline design can look like this.
.. code-block:: python
ap = ytree.AnalysisPipeline()
ap.add_recipe(gas_mass_recipe)
See the
:func:`~ytree.analysis.analysis_pipeline.AnalysisPipeline.add_recipe`
docstring for an example of including additional function arguments.
.. _parallel_analysis:
Putting it all Together: Parallel Analysis
------------------------------------------
To unleash the true power of the
:class:`~ytree.analysis.analysis_pipeline.AnalysisPipeline`, run it in
parallel using one of the :ref:`parallel_iterators`. See
:ref:`ytree_parallel` for more information on using ``ytree`` on
multiple processors.
.. code-block:: python
import ytree
a = ytree.load("arbor/arbor.h5")
if "test_field" not in a.field_list:
a.add_analysis_field("gas_mass", default=-1, units="Msun")
ap = ytree.AnalysisPipeline()
ap.add_recipe(gas_mass_recipe)
trees = list(a[:])
for node in ytree.parallel_nodes(trees):
ap.process_target(node)
If you need some inspiration, have a look at some :ref:`examples`.
| ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/doc/source/Analysis.rst | Analysis.rst |
---
title: 'ytree: A Python package for analyzing merger trees'
tags:
- Python
- astronomy
- astrophysics
- merger tree
- structure formation
- galaxies
authors:
- name: Britton D. Smith
orcid: 0000-0002-6804-630X
affiliation: 1
- name: Meagan Lang
orcid: 0000-0002-2058-2816
affiliation: 2
affiliations:
- name: University of Edinburgh
index: 1
- name: University of Illinois at Urbana-Champaign
index: 2
date: 4 October 2019
bibliography: paper.bib
---
# Summary
The formation of cosmological structure is dominated, especially on
large scales, by the force of gravity. In the early Universe, matter
is distributed homogeneously, with only small fluctuations about the
average density. Overdense regions undergo gravitational collapse to
form bound structures, called halos, which will host galaxies within
them. Halos grow via accretion of the surrounding material and by
merging with other halos. This process of merging to form increasingly
massive halos is naturally conceptualized as an inverted tree, where
small branches connect up to continually larger ones, leading
eventually to a trunk.
One of the main products of cosmological simulations is a series of
catalogs of halos within the simulated volume at different
epochs. Halos within successive epochs can be linked together to
create merger trees that describe a halo’s growth history. An example
of such a merger tree is shown in Figure 1. A variety of algorithms
and software packages exist for both halo identification and merger
tree calculation, resulting in a plethora of different data formats
that are non-trivial to load back into memory. A range of negative
consequences arise from this situation, including the difficulty of
comparing methods or scientific results and users being locked into
less than ideal workflows.
![A visualization of a merger tree. Each circle represents a halo with
lines connecting it to its descendent upward and its ancestors
downward, with the size of the circle proportional to the halo's
mass. Red circles denote the line of the most massive ancestors
of the primary halo at a given epoch. The merger tree was created
with the ``consistent-trees`` [@ctrees] merger tree code, loaded by
``ytree``, and visualized with ``pydot`` [@pydot] and ``graphviz``
[@graphviz].](tree.png)
The ``ytree`` package [@ytree] is an extension of the ``yt`` analysis
toolkit [@yt] for ingesting and analyzing merger tree data from
multiple sources. The ``ytree`` package provides a means to load
diverse merger tree data sets into common Python data structures,
analogous to what ``yt`` does for spatial data. A merger tree data set
loaded by ``ytree`` is returned to the user as a NumPy [@numpy] array
of objects representing the final halo, or node, in each merger
tree. Each node object contains pointers to node objects representing
its immediate ancestors and descendent. This allows the user to
intuitively navigate the tree structure.
Data fields, such as position, velocity, and mass, can be queried for
any node object, for the entire tree stemming from a given node, or
for just the line of most significant progenitors (typically the most
massive). Field data are returned as ``unyt_quantity`` or
``unyt_array`` objects [@unyt], subclasses of the NumPy array with
support for symbolic units. All data structure creation and field data
loading is done on-demand to limit unnecessary computation. Analogous
to ``yt``, derived fields can be created as linear combinations of any
existing fields by supplying a function that accepts a dictionary-like
object that can be expected to contain arrays of the dependent field
data. Any portion of a merger tree data set can be saved to a
``ytree`` format (based on HDF5 and using ``h5py`` [@h5py]) that has
somewhat faster field loading than most of the supported data
formats. This also allows a subset of data to be extracted for greater
portability and for saving newly created fields resulting from
expensive analysis.
The ``ytree`` package has been used for semi-analytic galaxy formation
models [@cote2018]; following halo trajectories in zoom-in simulations
[@hummels2019]; and for studying simulated galaxy properties
[@smith2018; @garrisonkimmel2019].
# Acknowledgements
Britton acknowledges the amazing ``yt`` community for being amazing as
well as financial support from NSF grant AST-1615848. M. Lang would
like to acknowledge the Gordon and Betty Moore Foundation’s
Data-Driven Discovery Initiative for supporting her contributions to
this work through Grant GBMF4561 to Matthew Turk.
# References
| ytree | /ytree-3.1.1.tar.gz/ytree-3.1.1/paper/paper.md | paper.md |
============
Contributing
============
Contributions are welcome, and they are greatly appreciated! Every
little bit helps, and credit will always be given.
You can contribute in many ways:
Types of Contributions
----------------------
Report Bugs
~~~~~~~~~~~
Report bugs at https://github.com/ashwinjv/ytrie/issues.
If you are reporting a bug, please include:
* Your operating system name and version.
* Any details about your local setup that might be helpful in troubleshooting.
* Detailed steps to reproduce the bug.
Fix Bugs
~~~~~~~~
Look through the GitHub issues for bugs. Anything tagged with "bug"
is open to whoever wants to implement it.
Implement Features
~~~~~~~~~~~~~~~~~~
Look through the GitHub issues for features. Anything tagged with "feature"
is open to whoever wants to implement it.
Write Documentation
~~~~~~~~~~~~~~~~~~~
ytrie could always use more documentation, whether as part of the
official ytrie docs, in docstrings, or even on the web in blog posts,
articles, and such.
Submit Feedback
~~~~~~~~~~~~~~~
The best way to send feedback is to file an issue at https://github.com/ashwinjv/ytrie/issues.
If you are proposing a feature:
* Explain in detail how it would work.
* Keep the scope as narrow as possible, to make it easier to implement.
* Remember that this is a volunteer-driven project, and that contributions
are welcome :)
Get Started!
------------
Ready to contribute? Here's how to set up `ytrie` for
local development.
1. Fork_ the `ytrie` repo on GitHub.
2. Clone your fork locally::
$ git clone [email protected]:your_name_here/ytrie.git
3. Create a branch for local development::
$ git checkout -b name-of-your-bugfix-or-feature
Now you can make your changes locally.
4. When you're done making changes, check that your changes pass style and unit
tests, including testing other Python versions with tox::
$ tox
To get tox, just pip install it.
5. Commit your changes and push your branch to GitHub::
$ git add .
$ git commit -m "Your detailed description of your changes."
$ git push origin name-of-your-bugfix-or-feature
6. Submit a pull request through the GitHub website.
.. _Fork: https://github.com/Nekroze/ytrie/fork
Pull Request Guidelines
-----------------------
Before you submit a pull request, check that it meets these guidelines:
1. The pull request should include tests.
2. If the pull request adds functionality, the docs should be updated. Put
your new functionality into a function with a docstring, and add the
feature to the list in README.rst.
3. The pull request should work for Python 2.6, 2.7, and 3.3, and for PyPy.
Check https://travis-ci.org/ashwinjv/ytrie
under pull requests for active pull requests or run the ``tox`` command and
make sure that the tests pass for all supported Python versions.
Tips
----
To run a subset of tests::
$ py.test test/test_ytrie.py
| ytrie | /ytrie-0.1.0.tar.gz/ytrie-0.1.0/CONTRIBUTING.rst | CONTRIBUTING.rst |
#########################################
YTRSS - subscription downloader
#########################################
Program to automatic download any types of files from Internet.
.. image:: https://img.shields.io/badge/author-Rafa%C5%82%20Kobel-blue.svg
:target: https://rafyco.pl
.. image:: https://github.com/rafyco/ytrss/actions/workflows/pythonpackage.yml/badge.svg?branch=develop
:target: https://github.com/rafyco/ytrss/actions/workflows/pythonpackage.yml
.. image:: https://img.shields.io/readthedocs/ytrss.svg
:target: https://ytrss.readthedocs.io
.. image:: https://img.shields.io/github/last-commit/rafyco/ytrss.svg
:target: https://github.com/rafyco/ytrss
.. image:: https://img.shields.io/github/issues/rafyco/ytrss.svg
:target: https://github.com/rafyco/ytrss/issues
.. image:: https://img.shields.io/pypi/v/ytrss.svg
:target: https://pypi.python.org/pypi/ytrss/
.. image:: https://img.shields.io/github/license/rafyco/ytrss.svg
:target: https://www.gnu.org/licenses/gpl.html
*************
Description
*************
YTRSS is a program that checks defined sources and downloads a movie or sound files
from them and arrange them to podcast files. It can be highly configured with many plugins
that add any other destinations.
The program in basic version use `youtube_dl` script to download files, so it cooperates
with all services implements by this library. However user can extends this capabilities by
his own custom plugins with external Downloaders.
Fast start
==========
The installation can be carried out in two ways. You can download
packages from PyPi repository or install it from sources.
For installation from PyPi you can use ``pip`` program. It is likely
that you must use ``pip3`` instead ``pip``.
.. code::
pip install ytrss
You can also use source from github repository to install ``ytrss``. To
make that download code and invoke command:
.. code::
python setup.py install
To checking the installation you can use to call ``ytrss``.
.. code::
$ ytrss --help
For more information about installation, configuration and bash completion read the documentation.
********
Author
********
Rafal Kobel [email protected]
.. image:: https://img.shields.io/static/v1.svg?label=Linkedin&message=Rafal%20Kobel&color=blue&logo=linkedin
:target: https://www.linkedin.com/in/rafa%C5%82-kobel-03850910a/
.. image:: https://img.shields.io/static/v1.svg?label=Github&message=rafyco&color=blue&logo=github
:target: https://github.com/rafyco
.. image:: https://img.shields.io/static/v1.svg?label=Facebook&message=Rafal%20Kobel&color=blue&logo=facebook
:target: https://facebook.com/rafyco
| ytrss | /ytrss-0.3.4rc3.tar.gz/ytrss-0.3.4rc3/README.rst | README.rst |
import requests
from bs4 import BeautifulSoup
import argparse
def main():
# First argument is the movie name
parser = argparse.ArgumentParser()
parser.add_argument('movie', type=str,
help='Movie name in single quotes')
args = parser.parse_args()
name = args.movie.lower()
try:
r = requests.get('https://yts.lt/browse-movies', timeout=7)
except requests.Timeout:
print('Request timeout')
else:
soup = BeautifulSoup(r.text, 'html.parser')
h2 = soup.find_all('h2')
movie_count = int((str(h2)[5:11].replace(',', '')))
titles = []
ids = []
page = 1
while True and page < movie_count / 50:
# Parameters to be added at the end of the url
payload = {
'limit': 50,
'page': page
}
r = requests.get(
'https://yts.lt/api/v2/list_movies.json', params=payload)
print("Searching on page: " + str(page))
if(r.status_code != 200):
print('Unable to get data\nExiting!')
exit()
# Using json method, since the response is in json
r_dict = r.json()
for i in range(payload['limit']):
titles.append(r_dict['data']['movies'][i]['title'])
ids.append(r_dict['data']['movies'][i]['id'])
count = 0
val = 0
flag = 0
for title in titles:
if name in title.lower():
print('Title is available!')
val = count
flag = 1
else:
count += 1
if(flag == 0):
pass
else:
finalTitle = titles[val]
finalId = ids[val]
payload = {
'movie_id': finalId
}
r = requests.get(
'https://yts.lt/api/v2/movie_details.json', params=payload)
r_new_dict = r.json()
print("\n")
print("Choose your option:")
for index, url in enumerate(r_new_dict['data']['movie']['torrents']):
print(str(index + 1) + "\tQuality: " + url['quality'] + "\t" +
"Size: " + url['size'] + "\t" + "Type: " + url['type'])
url_count = len(r_new_dict['data']['movie']['torrents'])
print(
str(url_count + 1) + "\tExit")
choice = int(input())
if(choice == url_count + 1):
exit()
with open(finalTitle.replace(':', '') + r_new_dict['data']['movie']['torrents'][choice - 1]['quality'] + '.torrent', 'wb') as f:
f.write(requests.get(
r_new_dict['data']['movie']['torrents'][choice - 1]['url']).content)
exit()
page += 1
payload['page'] = page
r_dict.clear()
del titles[:]
del ids[:]
print("Movie not found")
# Uncomment this for testing
if __name__ == "__main__":
main() | yts-downloader | /yts_downloader-0.1.2-py3-none-any.whl/yts_downloader/yts_downloader.py | yts_downloader.py |
MIT License
Copyright (c) 2022 Aqdas Ahmad Khan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
| ytsort | /ytsort-1.3.0-py3-none-any.whl/ytsort-1.3.0.dist-info/LICENSE.md | LICENSE.md |
# YT-Space
A terminal based YouTube video and music downloader, it uses the python package called `pytube` to download them from YT.
This is my school project on Python-MySQL connectivity.
<br/>
# Installation
To install this project, clone this repository and run `main.py`. You need to have Python3.6 or newer and MySQL server installed already. To install other required modules, execute this in your terminal.
```
$ pip install mysql-connector pytube
```
Now clone this repository and run `main.py`
```
$ git clone https://github.com/Yugam4254/YT-Space.git
$ cd YT-Space
$ python main.py
```
# How To Use
After running `main.py` you'll be prompted to enter your local MySQL server username and password.
<img src="https://cdn.discordapp.com/attachments/935157640256970782/935158571656699974/unknown.png" alt="login" width="300" height="">
After the successful login, you can choose from the following 8 menu options to continue.
<img src="https://cdn.discordapp.com/attachments/935157640256970782/935159345786798100/unknown.png" alt="menu" width="450" height="">
Example of downloading a song:
<img src="https://cdn.discordapp.com/attachments/935157640256970782/935161022690525195/unknown.png" alt="downloading a song" width="" height="">
<hr/>
Thank you for checking out my project. | ytspace | /ytspace-14.83.tar.gz/ytspace-14.83/README.md | README.md |
# YTSpider
YouTube Scraper (Un-official API)
Available features:
- videos
- comments
- transcripts
- channels
- playlists.
# Installation
pip install ytspider
# Usage
<h2>Scrape Videos</h2>
```
from ytspider import YTSVideo
vid_id = "jNQXAC9IVRw"
video = YTSVideo()
video.scrape(vid_id)
videoData = video.get()
```
<h2>Scrape Videos with Comments</h2>
```
from ytspider import YTSVideo
vid_id = "jNQXAC9IVRw"
video = YTSVideo()
video.scrape(vid_id).withComments(n_comments=100)
videoData = video.get()
```
```.get()``` returns ```dict<str, dict>```, str is videoId, dict is data
Now you have list of comments in ```videoData[vid_id]["comments"]```
Or you can set a default behavior for scraping comments
without calling ```withComments()``` each time
```
video = YTSVideo(commentScrapingBehavior="scrape") # ("scrape", "ignore" or None, Custom Behavior)
```
<h2>Scrape Channels</h2>
```
from ytspider import YTSChannel
channel_url = "https://www.youtube.com/@jawed" # or just screen-name @jawed
channel = YTSChannel()
channel.scrape(channel_url)
channelData = channel.get()
```
```.get()``` returns ```dict<str, dict>```, ```str``` is channel Id, ```dict``` is data
<h2>Scrape Channels with Videos</h2>
```
from ytspider import YTSChannel
channel_url = "https://www.youtube.com/@jawed" # or just screen-name @jawed
channel = YTSChannel()
channel.scrape(channel_url).withVideos(n_videos=29)
channelData = channel.get()
# .get() returns dict<str, dict>, str is channel Id, dict is data
# Now you have list of videos in channelData["@jawed"]["videos"]
```
# Software Extensibility
<h2>Custom Behaviors (Decorators)</h2>
How to add your own behavior for scraping comments, transcriptions, or additional capabilities<br>
Will be documented soon | ytspider | /ytspider-0.0.0.5.tar.gz/ytspider-0.0.0.5/README.md | README.md |
import re
import json
import requests
from bs4 import BeautifulSoup
from .utils.handler import BaseHandler
from .utils.decorator import VideosScraper, CommentScraper, TranscriptScraper
from .utils.request import Request
from .utils.context import Context
# This package was built on hurry, I'll comment it later
class YTSpider:
def __init__(self):
self.Request = Request()
self.__Response = {}
self.__Context = Context()
self.handlers = {}
self.defaultHandlers = {}
self.itemId = []
def attachHandler(self, handler):
if not isinstance(handler, BaseHandler):
raise ValueError(
"Argument (handler) must be a subclass of BaseHandler")
if not handler.name in self.defaultHandlers:
self.defaultHandlers[handler.name] = handler
self.handlers[handler.name] = handler
def restoreDefaultHandlers(self, exclude=[]):
for handlerName in self.defaultHandlers:
if handlerName not in exclude:
self.handlers[handlerName] = self.defaultHandlers[handlerName]
def removeHandler(self, handler):
if handler.name in self.handlers:
del self.handlers[handler.name]
return True
return False
def getHandler(self, handlerName):
if handlerName in self.handlers:
return self.handlers[handlerKey]
return None
def getAllHandlers(self):
return self.handlers
def executeHandlers(self, itemId):
results = {}
for handlerName, handler in self.handlers.items():
result = handler.execute(itemId)
if result is not None and result != []:
results[handlerName] = result
return results
def scrape(self, itemId, continuation_token=None):
self.__Response.clear()
if type(itemId) == str:
# self.itemId = itemId
# self.__Response.update({itemId: self.scrapeSingle(itemId)})
result = self.scrapeSingle(itemId)
key = self.itemId[0] if (len(self.itemId) > 0) else "undefined"
self.__Response.update({key: result})
elif type(itemId) == list:
for i, id in enumerate(itemId):
if type(id) == str:
# self.__Response.update({id: self.scrapeSingle(id)})
result = self.scrapeSingle(id)
key = self.itemId[i] if hasattr(self, "itemId") else id
self.__Response.update({key: result})
else:
raise ValueError(
f"Invalid data type at index {i}. Expected str")
return self
def scrapeSingle(self, itemId):
result = {itemId: None}
return result
def get(self):
for itemId in self.__Response.keys():
# self.itemId = itemId
result = self.executeHandlers(itemId)
# Set result in response item if and only if result contains data
if result is not None:
if itemId in self.__Response:
# Sometimes, scraper has itemId, but no results (None)
# in this case, just attach whatever the handler's got
if self.__Response[itemId] is None:
self.__Response[itemId] = result
else:
self.__Response[itemId].update(result)
else:
self.__Response[itemId] = result
self.restoreDefaultHandlers()
return self.__Response
class YTSVideo(YTSpider, CommentScraper, TranscriptScraper):
def __init__(self, commentDefaultHandler=None, transcriptDefaultHandler=None):
super(YTSVideo, self).__init__()
CommentScraper.__init__(self, commentDefaultHandler)
TranscriptScraper.__init__(self, transcriptDefaultHandler)
self.url = "https://www.youtube.com/youtubei/v1/player?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8&prettyPrint=false"
def scrapeSingle(self, itemId):
self.Request.updateContextState(itemId)
result = self.Request.send(self.url, "POST")
if "videoDetails" in result:
self.itemId.append(result["videoDetails"]["videoId"])
return result["videoDetails"]
return None
class YTSChannel(YTSpider, VideosScraper):
def __init__(self, videosDefaultHandler=None):
super(YTSChannel, self).__init__()
VideosScraper.__init__(self, videosDefaultHandler)
self.url = "https://www.youtube.com/"
def prepareURL(self, userInput):
if type(userInput) != str:
raise ValueError("Argument (screenName) must be a string")
screenNames = re.findall(r"@\w+", userInput)
if len(screenNames) > 0:
screenName = screenNames[0]
elif "youtube.com" in userInput:
screenName = ""
self.url = userInput
else:
raise ValueError(
"Argument (screenName) must have a screen name as '@ChannelName' or a YouTube URL")
return self.url + screenName.strip("/").strip()
def __postProcessResponse(self, response):
if isinstance(response, requests.models.Response):
soup = BeautifulSoup(response.text)
# print(list(map(lambda x: x['itemprop'], metas)))
data = {}
# FEATURE: add useful meta properties (attributes['property'])
attributes = {
"itemprop": [
"channelId",
"isFamilyFriendly",
"regionsAllowed",
"paid",
"name",
"url"
],
"name": [
"description",
"keywords"
],
"property": []
}
thumbnailUrl = soup.find("link", {"itemprop": "thumbnailUrl"})
if thumbnailUrl is not None:
thumbnailUrl = thumbnailUrl['href']
for criteria in attributes:
for metaKey in attributes[criteria]:
tag = soup.find("meta", {criteria: metaKey})
if tag is not None:
tagInnerContent = tag['content']
data[metaKey] = tagInnerContent
# Sometimes, response does not include channelId in meta tags
# In this case -> brute-force extract channelId from embedded JS code
if "channelId" not in data:
channelIds = re.findall(r'"browseId":"([a-zA-Z0-9 _ -]+)"', str(soup))
if len(channelIds) > 0:
data["channelId"] = channelIds[0]
# print("ACTUATED CHANNEL " + channelIds[0])
self.itemId.append(data["channelId"])
# channelId is found in HTML meta tags
else:
# print("SELF EXTRACTED " + data["channelId"])
self.itemId.append(data["channelId"])
return data
def scrapeSingle(self, screenName):
endpoint = self.prepareURL(screenName)
result = self.Request.send(endpoint)
data = self.__postProcessResponse(result)
return data | ytspider | /ytspider-0.0.0.5.tar.gz/ytspider-0.0.0.5/src/ytspider.py | ytspider.py |
from .request import Request
class BaseHandler:
def __init__(self, name=None):
self.request = Request()
self.name = name
def execute(self, itemId):
return None
class CommentHandler(BaseHandler):
def __init__(self, n_comments=0):
super(CommentHandler, self).__init__(name='comments')
self.n_comments = n_comments
def execute(self, itemId):
return None
class CommentDefaultHandler(CommentHandler):
def __init__(self, n_comments=0):
super(CommentDefaultHandler, self).__init__(n_comments)
def execute(self, itemId):
return None
class CommentScrapingHandler(CommentHandler):
def __init__(self, n_comments=100):
super(CommentScrapingHandler, self).__init__(n_comments)
self.url = "https://www.youtube.com/youtubei/v1/next?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8&prettyPrint=false"
def execute(self, itemId):
self.request.updateContextState(itemId, additional={"continuation": ""})
firstTime = True
token = ""
all_comments = []
while token is not None and len(all_comments) < self.n_comments:
self.request.updateContextState(additional={"continuation": token})
result = self.request.send(self.url, method="POST")
comments = []
if firstTime:
# Try get token for comment retrieval
try:
token = result["contents"]["twoColumnWatchNextResults"]["results"]["results"]["contents"][3]["itemSectionRenderer"]["contents"][0]["continuationItemRenderer"]["continuationEndpoint"]["continuationCommand"]["token"]
firstTime = False
# Couldn't get token for comment retrieval
except Exception as e:
token = None
else:
# Try get comments
try:
commentsContainer = result["onResponseReceivedEndpoints"][-1]["reloadContinuationItemsCommand"]["continuationItems"]
# If it's only one comment on the video, get it
if len(commentsContainer) == 1:
comments = [commentsContainer[0]]
# +2 comments, grab all but the last item (token)
else:
comments = commentsContainer[:-1]
# There are no comments at all (not a single one!)
except Exception as e:
pass
# Try get token, but if comments are < 20, there is no 'continuation' token because there're no more comments
try:
token = result["onResponseReceivedEndpoints"][-1]["reloadContinuationItemsCommand"]["continuationItems"][-1]["commentThreadRenderer"]["continuationEndpoint"]["continuationCommand"]["token"]
# No more comments
except Exception as e:
token = None
for i in range(len(comments)):
comment_texts = comments[i]["commentThreadRenderer"]["comment"]["commentRenderer"]["contentText"]['runs']
comment = " ".join(
list(map(lambda c: c["text"], comment_texts)))
all_comments.append(comment)
return all_comments
class TranscriptionHandler(BaseHandler):
def __init__(self, only_in_langs=[]):
super(TranscriptionHandler, self).__init__(name='transcripts')
self.only_in_langs = only_in_langs
def execute(self, itemId):
return None
class TranscriptionScrapingHandler(TranscriptionHandler):
def __init__(self, only_in_langs=[]):
super(TranscriptionScrapingHandler, self).__init__(only_in_langs)
def execute(self, itemId):
result = ["One Two THree"]
return result
class TranscriptionDefaultHandler(TranscriptionHandler):
def __init__(self):
super(TranscriptionDefaultHandler, self).__init__()
def execute(self, itemId):
return None
class VideosHandler(BaseHandler):
def __init__(self, n_videos=0):
super(VideosHandler, self).__init__(name='videos')
self.n_videos = n_videos
def execute(self, itemId):
return None
class VideosDefaultHandler(VideosHandler):
def __init__(self, n_videos=0):
super(VideosDefaultHandler, self).__init__(n_videos)
def execute(self, itemId):
return None
class VideosScrapingHandler(VideosHandler):
def __init__(self, n_videos=29):
super(VideosScrapingHandler, self).__init__(n_videos)
self.url = "https://www.youtube.com/youtubei/v1/browse?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8&prettyPrint=false"
def execute(self, itemId):
params_token = ""
firstTime = True
token = ""
all_videos = []
self.request.updateContextState(additional={"browseId": itemId, "params": params_token})
# Scrape MainPage tab
result = self.request.send(self.url, "POST")
try:
# Get param which will route the scraping to Videos Tab
tabs = result["contents"]["twoColumnBrowseResultsRenderer"]["tabs"]
if len(tabs) > 2 and tabs[1]["tabRenderer"]["title"] == "Videos":
vidTabsEndPointParam = tabs[1]["tabRenderer"]["endpoint"]["browseEndpoint"]["params"]
self.request.updateContextState(additional={"params": vidTabsEndPointParam})
# Scrape Videos Tab
result = self.request.send(self.url, "POST")
tabs = result["contents"]["twoColumnBrowseResultsRenderer"]["tabs"]
videoItems = tabs[1]["tabRenderer"]["content"]["richGridRenderer"]["contents"]
# Remove unnecessary request payload
self.request.updateContextState(removables=["params", "browseId"])
while len(all_videos) < self.n_videos:
for videoItem in videoItems[:-1]:
vidRender = videoItem["richItemRenderer"]["content"]["videoRenderer"]
video = {}
video["id"] = vidRender["videoId"]
video["title"] = vidRender["title"]["runs"][0]["text"]
video["views_count"] = vidRender["viewCountText"]["simpleText"]
video["publish_at"] = vidRender["publishedTimeText"]["simpleText"]
if len(all_videos) >= self.n_videos:
return all_videos
all_videos.append(video)
try:
# Set Continuation Parameter
continuationParam = videoItems[-1]["commentThreadRenderer"]["continuationEndpoint"]["continuationCommand"]["token"]
except Exception as e:
print(e)
break
self.request.updateContextState(additional={"continuation":continuationParam})
result = self.request.send(self.url, "POST")
try:
videoItems = result["onResponseReceivedActions"][0]["appendContinuationItemsAction"]["continuationItems"]
except Exception as e:
print(e)
break
except Exception as e:
print(e)
pass
return all_videos
# # TODO: Scrape for first time to get "params", then use tabs[1] to get params and scrape Videos tab[1]
# # What about making one class 'ChannelTabHandler' which takes tab name (videos, playlists), nope because each has different output (solvable but code more for fun) | ytspider | /ytspider-0.0.0.5.tar.gz/ytspider-0.0.0.5/src/utils/handler.py | handler.py |
from .handler import *
class ScrapingDecorator:
def __init__(self, defaultHandler=BaseHandler()):
if not isinstance(defaultHandler, BaseHandler):
raise ValueError(
"Argument (defaultHandler) must be a subclass of BaseHandler or 'scrape' or 'ignore'")
self.defaultHandler = defaultHandler
def setDefaultHandler(self, defaultHandler):
if defaultHandler is None:
raise ValueError(
"Argument (defaultHandler) must be a subclass of parent (BaseHandler)")
self.defaultHandlers[defaultHandler.name] = defaultHandler
self.updateHandler(defaultHandler)
def updateHandler(self, handler):
if not isinstance(handler, BaseHandler):
raise ValueError(
"Argument (handler) must be a subclass of BaseHandler")
self.attachHandler(handler)
class VideosScraper(ScrapingDecorator):
def __init__(self, videosDefaultHandler=VideosDefaultHandler()):
if videosDefaultHandler is None or commentDefaultHandler == 'ignore':
videosDefaultHandler = VideosDefaultHandler()
elif videosDefaultHandler == 'scrape':
videosDefaultHandler = VideosScrapingHandler()
super(VideosScraper, self).__init__(videosDefaultHandler)
self.updateHandler(videosDefaultHandler)
def withVideos(self, n_videos=29):
handler = VideosScrapingHandler(n_videos=n_videos)
self.updateHandler(handler)
return self
class TranscriptScraper(ScrapingDecorator):
def __init__(self, transcriptDefaultHandler=TranscriptionDefaultHandler()):
if transcriptDefaultHandler is None or transcriptDefaultHandler == 'ignore':
transcriptDefaultHandler = TranscriptionDefaultHandler()
elif transcriptDefaultHandler == 'scrape':
transcriptDefaultHandler = TranscriptionScrapingHandler()
super(TranscriptScraper, self).__init__(transcriptDefaultHandler)
self.updateHandler(transcriptDefaultHandler)
def withTranscripts(self, only_in_langs=[]):
handler = TranscriptionScrapingHandler(only_in_langs=only_in_langs)
self.updateHandler(handler)
return self
class CommentScraper(ScrapingDecorator):
def __init__(self, commentDefaultHandler=CommentDefaultHandler()):
if commentDefaultHandler is None or commentDefaultHandler == 'ignore':
commentDefaultHandler = CommentDefaultHandler()
elif commentDefaultHandler == 'scrape':
commentDefaultHandler = CommentScrapingHandler()
super(CommentScraper, self).__init__(commentDefaultHandler)
self.updateHandler(commentDefaultHandler)
def withComments(self, n_comments=15):
handler = CommentScrapingHandler(n_comments=n_comments)
self.updateHandler(handler)
return self | ytspider | /ytspider-0.0.0.5.tar.gz/ytspider-0.0.0.5/src/utils/decorator.py | decorator.py |
import requests
from .context import Context
from bs4 import BeautifulSoup
class Request:
def __init__(self):
self.__Context = Context()
self.__initHeaders()
def __initHeaders(self):
self.headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Credentials": "include"
}
def addHeaders(self, headers):
self.headers.update(headers)
def removeHeaders(self, headerNames):
for key in headerNames:
self.headers.pop(key)
def updateContextState(self, videoId=None, replacables={}, additional={}, removables=[]):
if videoId is not None:
self.__Context.replaceVideoId(videoId)
for key, val in replacables.items():
if key in self.__Context:
self.__Context[key] = val
else:
self.__Context.replace(key, val)
for key, val in additional.items():
self.__Context.add(key, val)
for key in removables:
if key in self.__Context.get():
self.__Context.remove(key)
else:
self.__Context.replace(key, '')
def send(self, url, method="GET", additional_payload=None):
if type(method) != str or method not in ["GET", "POST"]:
raise ValueError(
"Invalid 'method' value. must be either 'GET' or 'POST'")
# if type(payload) != dict:
# raise ValueError("Invalid 'payload' value. must be a dictionary")
if type(url) != str:
raise ValueError("Invalid 'url' value. must be a string")
# Merge payloads
payload = self.__Context.get()
# if additional_payload is not None and type(additional_payload) == dict:
# payt
# payload.update(additional_payload)
if method.upper() == "GET":
response = requests.get(url, headers = {
"Accept":"text/html"
})
elif method.upper() == "POST":
response = requests.post(
url,
json=payload,
headers=self.headers
)
if response.status_code == 200:
if method.upper() == "GET":
return response
elif method.upper() == "POST":
return response.json()
else:
# print(response.content)
raise RuntimeError(f"Request failed ({response.status_code})")
return None | ytspider | /ytspider-0.0.0.5.tar.gz/ytspider-0.0.0.5/src/utils/request.py | request.py |
import colorama,time
import json
from playsound import playsound
from pyfiglet import Figlet
import sys,os
import multiprocessing
import argparse
__version__="1.1.3"
glurl=""
FREE_API_KEY="AIzaSyA_qsbJMvLaklHfbLKMq4zaoVE-7UTTqcM"
'''Play function'''
def play():
playsound(glurl)
'''Multiprocessed play function end'''
def checkForGi():
if sys.platform=="linux":
try:
from gi import require_version
except:
print(colorama.Fore.RED+"Please install gstreamer bindings for python on linux to run ytstreamer"+colorama.Style.RESET_ALL)
quit()
def makeStreamable(string):
return "https://www.youtube.com/watch?v=" + string
def listToString(lst):
return "".join(lst)
def getResults(query):
streamableLinks=[]
from youtube_api import YoutubeDataApi
yt=YoutubeDataApi(FREE_API_KEY)
searches=yt.search(q=query,max_results=10)
for i in searches:
streamableLinks.append(makeStreamable(i["video_id"]))
return streamableLinks
def del0(lst):
if lst[0]=="0":
del lst[0]
return lst
def timeToInt(tstr):
components=tstr.split(":")
hourSubcomponents=list(components[0])
minSubcomponents=list(components[1])
secComponents=list(components[2])
hourSubcomponents=3600 * int(listToString(del0(hourSubcomponents)))
minSubcomponents=60 * int(listToString(del0(minSubcomponents)))
secComponents=int(listToString(del0(secComponents)))
return hourSubcomponents+minSubcomponents+secComponents+2
def runmain():
import pafy
global glurl
colorama.init()
checkForGi()
cs_fig=Figlet(font="jazmine")
print(colorama.Fore.LIGHTGREEN_EX,cs_fig.renderText("Yt_Streamer"),colorama.Style.RESET_ALL)
try:
inp=input(colorama.Fore.CYAN+"Enter video query: "+colorama.Fore.YELLOW)
except KeyboardInterrupt:
print(colorama.Fore.RED+"Exited"+colorama.Style.RESET_ALL)
quit()
res=getResults(inp)
res_counter=1
while res_counter < len(res):
video=pafy.new(res[res_counter-1])
bestaudio=video.getbestaudio()
url=bestaudio.url
glurl=url
#xz=timeToInt(video.duration) not being used currently but is required for later versions where I'll be using a custom gst player instead of playsound
print(colorama.Fore.LIGHTMAGENTA_EX,f"Now playing[{res_counter}]: [{video.title}][{video.duration}][@{bestaudio.quality}]",colorama.Style.RESET_ALL)
process=multiprocessing.Process(target=play)
process.start()
try:
args=input("~ ")
except KeyboardInterrupt:
process.terminate()
print(colorama.Fore.RED+"\nStream Stopped"+colorama.Style.RESET_ALL)
break
if args.lower()=="quit" or args.lower()=="q":
process.terminate()
print(colorama.Fore.RED+"\nStream Stopped"+colorama.Style.RESET_ALL)
break
if args.lower()=="next" or args.lower()=="n":
process.terminate()
res_counter+=1
continue
if args.lower()=="restart" or args.lower()=="r":
process.terminate()
res_counter=1
continue
if args.lower=="previous" or args.lower()=="p":
process.terminate()
res_counter-=1
continue
print(colorama.Fore.RED+"\nQueue finished")
print("Exited")
def main():
parser=argparse.ArgumentParser()
parser.add_argument("-v","--version",dest="ver",action="store_true")
parser.add_argument("-hy","--yelp",dest="hbool",action="store_true")
recv_args=parser.parse_args()
if recv_args.ver:
print(__version__)
elif recv_args.hbool:
print("Help:\n\n-v or --version- Displays version\n-h or --help - Displays Help\n\nPlayer commands-\n\n1. n or next to get to the next stream\n2. q or quit to quit the script.(Ctrl-C also works)\n3. r or restart to restart the queue\n4. p or previous to go back to previous stream. ")
else:
runmain()
'''if __name__=="__main__":
main()''' | ytstreamer | /ytstreamer-1.1.4-py3-none-any.whl/src/streamer.py | streamer.py |
# Youtube Studio
Unofficial Async YouTube Studio API. Set of features limited or not provided by official YouTube API!
> This is the Python version of [this project](https://github.com/adasq/youtube-studio). All thanks going to [@adasq](https://github.com/adasq) :)
## Installation
You can install with [PIP](https://pypi.org/project/ytstudio/).
`pip install ytstudio`
## Features
Look at the documentation: [Click here](https://yusufusta.github.io/ytstudio/)
- Fully Async
- [Uploading Video](https://yusufusta.github.io/ytstudio/#ytstudio.Studio.uploadVideo) - [Example](https://github.com/yusufusta/ytstudio/blob/master/examples/upload_video.py) (**NOT LIMITED** - official API's videos.insert charges you 1600 quota units)
- [Deleting Video](https://yusufusta.github.io/ytstudio/#ytstudio.Studio.deleteVideo) - [Example](https://github.com/yusufusta/ytstudio/blob/master/examples/edit_video.py#L29)
- [Edit Video](https://yusufusta.github.io/ytstudio/#ytstudio.Studio.editVideo) - [Example](https://github.com/yusufusta/ytstudio/blob/master/examples/edit_video.py#L13)
- [Get Video(s)](https://yusufusta.github.io/ytstudio/#ytstudio.Studio.listVideos) - [Example](https://github.com/yusufusta/ytstudio/blob/master/examples/get_videos.py#L7)
## Login
You need cookies for login. Use an cookie manager([EditThisCookie](https://chrome.google.com/webstore/detail/editthiscookie/fngmhnnpilhplaeedifhccceomclgfbg?hl=tr)) for [needed cookies.](https://github.com/yusufusta/ytstudio/blob/master/examples/login.json)
Also you need SESSION_TOKEN for (upload/edit/delete) video. [How to get Session Token?](https://github.com/adasq/youtube-studio#preparing-authentication)
## TO-DO
- [ ] Better Documentation
- [ ] Better Tests
- [ ] More Functions
## Author
Yusuf Usta, [email protected]
## Note
This library is in no way affiliated with YouTube or Google. Use at your own discretion. Do not spam with this.
| ytstudio | /ytstudio-1.5.2.tar.gz/ytstudio-1.5.2/README.md | README.md |
=====
ytsub
=====
ytsub provides a command-line interface to do things with your Youtube subscriptions. You might find it most useful for filtering those
videos using grep, or setting up an auto-downloader using the excellent
youtube-dl. An example usage might look like this::
$ ytsub list | grep 'FTB\|Feed The Beast' | awk -F"\t" '{print $2}' | tee >(youtube-dl -a /dev/stdin >/dev/tty) | ytsub mark-watched
The above gets list of all unwatched subscription videos, filters out ones that don't include the string 'FTB' or 'Feed The Beast' in their titles, gets youtube-dl to start downloading them, and marks them as watched.
install
=======
Installing is pretty easy on linux systems
1. Install pip (python package manager) if you don't have it::
$ sudo apt-get install python-pip
2. Download ytsub. To get the latest stable release, head to https://github.com/JWill392/ytsub/tags and click one of the download links for the latest tag.
3. Open archive, take out the archive in /dist -- should look like: ytsub-<version number>.tar.gz. Don't uncompress it.
4. Run pip install with the dist archive::
$ sudo pip install ytsub-<version number>.tar.gz --upgrade
That's it. It's runnable like any other command::
$ ytsub list -c 1 -t 0
Alternatively, you can use git:
1. sudo apt-get install python-pip git
2. git clone -b release https://github.com/JWill392/ytsub.git
3. sudo pip install ytsub/dist/<press tab -- should be just the one dist archive in here> --upgrade
4. rm -rf ytsub
| ytsub | /ytsub-1.2.1.tar.gz/ytsub-1.2.1/README.txt | README.txt |
import os
import logging
from PIL import Image
logger = logging.getLogger('custom_image_utils')
class CustomImage(Image.Image):
"""
Simple image creation API using PIL Library
"""
default_image_path = None
default_mode = '1' # 1-bit pixels, black and white, stored with one pixel per byte
default_size = (1,1) # Single Pixel
default_color = 0 # Black
def __init__(self, **kwargs):
"""
creates an empty image using the settings as a placeholder
:param kwargs: Settings (Default Image size , Default Color ...)
"""
self.settings = kwargs
self.image = self.create_default_image()
self.image_path = CustomImage.default_image_path
def create_default_image(self):
"""
Creates an empty single pixel image and set image attribute
"""
self.image = Image.new(CustomImage.default_mode,
CustomImage.default_size,
CustomImage.default_color)
logger.debug('Default image created')
def change_image_path(self, image_path):
if self.is_valid_path(image_path) is True:
self.image_path = image_path
def open_image(self, image_path):
"""
sets image attribute to an Image type
:param image_path:
"""
if self.is_valid_path(image_path) is True:
self.image = Image.open(image_path)
logger.info(f'image from {image_path} opened')
def get_image_data(self):
"""
Get the data from image_data attribute
"""
self.image_data = self.image.getdata()
logger.debug(f'Image data :\n{self.image_data}')
def convert_image(self, mode):
"""
Available modes:
https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes
"""
self.image.convert(mode)
logger.info(f'Image converted to {mode}')
def change_image_color(self, new_color=(0, 0, 0)):
"""
Appends a new color to image_data
"""
for item in self.image_data:
if item[0] in list(range(200, 256)):
new_image_data.append(new_color)
else:
new_image_data.append(item)
logger.info(f'New color to {new_color}')
def save_image(self, path):
"""
Saves the image to path location
:param path:
"""
self.image.save(path)
logger.debug('image saved to {}'.format(path))
def is_valid_path(self, path):
valid = False
# Path exists
if os.path.exists(path) is True:
valid = True
else:
logger.info(f'{path} does not exist')
return valid
def example():
"""
Simple example using this class
"""
icon = CustomImage()
icon.open_image('ressources/eye_open.png')
print(icon)
# pink_color = (255, 0, 0)
# new_image_data = change_color(data, pink_color)
#
# im.putdata(new_image_data)
# im.show()
# save_path = r"C:\Users\youss\Desktop\flower_image_altered.jpg"
# save_image(im, save_path)
example() | ytt-py-utils | /ytt_py_utils-0.0.2-py3-none-any.whl/ytt_py_utils/img/Pillow/image.py | image.py |
from PySide2.QtGui import QSyntaxHighlighter, QTextCharFormat, QFont
from PySide2.QtWidgets import QWidget, QVBoxLayout, QTabWidget, QStackedWidget
from PySide2.QtCore import Qt, QRegExp
class Tab(QWidget):
"""
Tab
"""
def __init__(self):
"""
"""
super(Tab).__init__()
self.layout = QVBoxLayout(self)
# Initialize tab
self.tabs = QTabWidget()
self.tabs.setStyleSheet("background-color: #36302E;"
"border :1px solid ;")
# Documentation Tab
self.doc_tab = QWidget()
# Source Tab
self.source_tab = QWidget()
self.tabs.resize(300, 200)
# Add tabs
self.tabs.addTab(self.doc_tab, "Doc")
self.tabs.addTab(self.source_tab, "Source")
# Doc Tab
self.doc_tab.layout = QVBoxLayout(self)
self.text_edit_doc = txt_cls.DocTextEdit()
self.text_edit_doc.setReadOnly(True)
self.doc_tab.layout.addWidget(self.text_edit_doc)
self.doc_tab.setLayout(self.doc_tab.layout)
# Source Tab
self.source_tab.layout = QVBoxLayout(self)
self.text_edit_source = txt_cls.SourceTextEdit()
self.text_edit_source.setReadOnly(True)
self.source_tab.layout.addWidget(self.text_edit_source)
self.source_tab.setLayout(self.source_tab.layout)
# Add to Widget
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
class Highlighter(QSyntaxHighlighter):
"""
Highlighter
"""
def __init__(self, parent=None):
"""
:param parent:
"""
super(Highlighter, self).__init__(parent)
keyword_format = QTextCharFormat()
keyword_format.setForeground(Qt.green)
keyword_format.setFontWeight(QFont.Bold)
keyword_patterns = ["\\bchar\\b", "\\bclass\\b", "\\bconst\\b",
"\\bdouble\\b", "\\benum\\b", "\\bexplicit\\b", "\\bfriend\\b",
"\\binline\\b", "\\bint\\b", "\\blong\\b", "\\bnamespace\\b",
"\\boperator\\b", "\\bprivate\\b", "\\bprotected\\b",
"\\bpublic\\b", "\\bshort\\b", "\\bsignals\\b", "\\bsigned\\b",
"\\bslots\\b", "\\bstatic\\b", "\\bstruct\\b",
"\\btemplate\\b", "\\btypedef\\b", "\\btypename\\b",
"\\bunion\\b", "\\bunsigned\\b", "\\bvirtual\\b", "\\bvoid\\b",
"\\bvolatile\\b"]
self.highlightingRules = [(QRegExp(pattern), keyword_format)
for pattern in keyword_patterns]
class_format = QTextCharFormat()
class_format.setFontWeight(QFont.Bold)
class_format.setForeground(Qt.green)
self.highlightingRules.append((QRegExp("\\bQ[A-Za-z]+\\b"),
class_format))
single_line_comment_format = QTextCharFormat()
single_line_comment_format.setForeground(Qt.red)
self.highlightingRules.append((QRegExp("//[^\n]*"),
single_line_comment_format))
self.multiLineCommentFormat = QTextCharFormat()
self.multiLineCommentFormat.setForeground(Qt.red)
quotation_format = QTextCharFormat()
quotation_format.setForeground(Qt.darkYellow)
self.highlightingRules.append((QRegExp("\".*\""), quotation_format))
function_format = QTextCharFormat()
function_format.setFontItalic(True)
function_format.setForeground(Qt.cyan)
self.highlightingRules.append((QRegExp("\\b[A-Za-z0-9_]+(?=\\()"),
function_format))
self.commentStartExpression = QRegExp("/\\*")
self.commentEndExpression = QRegExp("\\*/")
def highlightBlock(self, text):
"""
:param text:
:return:
"""
for pattern, frmt in self.highlightingRules:
expression = QRegExp(pattern)
index = expression.indexIn(text)
while index >= 0:
length = expression.matchedLength()
self.setFormat(index, length, frmt)
index = expression.indexIn(text, index + length)
self.setCurrentBlockState(0)
start_index = 0
if self.previousBlockState() != 1:
start_index = self.commentStartExpression.indexIn(text)
while start_index >= 0:
end_index = self.commentEndExpression.indexIn(text, start_index)
if end_index == -1:
self.setCurrentBlockState(1)
comment_length = len(text) - start_index
else:
comment_length = end_index - start_index + self.commentEndExpression.matchedLength()
self.setFormat(start_index, comment_length,
self.multiLineCommentFormat)
start_index = self.commentStartExpression.indexIn(text,
start_index + comment_length)
class WidgetStack(QStackedWidget):
"""
WidgetStack
"""
def __init__(self):
"""
"""
super(WidgetStack, self).__init__()
self.layout = QVBoxLayout()
def add_widget(self, widget):
"""
:param widget:
:return:
"""
self.addWidget(widget)
widget.setLlayout(self.layout) | ytt-py-utils | /ytt_py_utils-0.0.2-py3-none-any.whl/ytt_py_utils/ui/Pyside2/others.py | others.py |
# YTTEXT
## Overview
The YTTEXT package provides a convenient way to scrape subtitles from YouTube videos and save them to text files. It offers a simple interface for retrieving and processing subtitles, making it easy to extract text data for analysis or other purposes.
<br></br>
## Installation
```
pip install yttext
```
upgrade
```
pip install --upgrade yttext
```
<br>
## Usage
To scrape the subtitles from any youtube video, simply call the get_text function with the video_id, and the text will be saved to <video_id>.txt.
```python
import yttext
video_id = 'IflfP4XwzAI'
yttext.get_text(video_id)
```
Output printed to console:
```
48773 words successfully scraped.
```
Optionally, you can specify a folder name to write the file to as well.
```python
video_id = 'IflfP4XwzAI'
yttext.get_text(video_id, folder='subtitles')
```
<br>
## Multiple video usage
To use the get_text function for a list of videos, you can simply call the function in a loop or iterate over the video IDs, and they will all be saved to a txt file with the cooresponding video ID.
```python
video_ids = ['video_id1', 'video_id2', 'video_id3']
for video_id in video_ids:
yttext.get_text(video_id)
# Optional: Specify folder for saving the text file
# yttext.get_text(video_id, folder='subtitles')
``` | yttext | /yttext-0.0.2.tar.gz/yttext-0.0.2/README.md | README.md |
<h1 align="center">Ytty - Powerful tool for parsing, downloading and uploading videos from youtube based on selenium.</h1>
<h1 align="center"> -WARINING!!!- </h1>
```
You must have Google Chrome installed for google auth bypass!
```
<h1 align="center"> -How to use?- </h1>
<h2 align="center"> -Quickstart- </h2>
```python
from ytty import *
if __name__ == '__main__':
session = shadowSession()
options = YTOptions()
options.parse.search = 'FREE FIRE MOD MENU'
options.parse.period = 1
options.parse.max = 10
videos = parseVideos(session, options)
video = getVideo(videos[0]['link'])
session.quit()
session = googleSession('login', 'password')
options.upload.video = video
options.upload.title = videos[0]['title']
options.upload.description = '''This you can write description for video
That text written for example, you can write this what do you want :)'''
options.upload.tags = ['tags', 'writes', 'in a', 'taglist', 'add', 'some tags', 'this']
options.upload.preview = getThumbnail(videos[0]['id'])
uploadVideo(session, options)
```
<h2 align="center"> -Parsing videos- </h2>
```python
from ytty import *
if __name__ == '__main__':
session = shadowSession() #headless chrome session without login
options = YTOptions()
options.parse.search = 'FREE FIRE MOD MENU' #Search request
options.parse.period = 1 #Period from 0 to 2 when -> 0 - Today | 1 - a Week | 2 - a Month (Default is 2)
options.parse.max = 10 #Limit of parsing video (Default is 20)
videos = parseVideos(session, options)
for video in videos:
title = video['title'] #video title
link = video['link'] #video link
id = video['id'] #video id
session.quit() #For close session
```
<h2 align="center"> -Download thumbnails (previews)- </h2>
```python
for video in videos:
getThumbnail(video['id']) #returns filename of preview
```
<h2 align="center"> -Download videos- </h2>
```python
for video in videos:
getVideo(video['link']) #returns filename of video
```
<h2 align="center"> -Download video with uniqualization- </h2>
```python
for video in videos:
options = YTOptions()
options.download.unique = True
getVideo(video['link'], options)
```
<h2 align="center"> -Upload videos- </h2>
```python
for video in videos:
session = googleSession('login', 'password') #session with login in google (no headless)
options = YTOptions()
options.upload.video = 'C:/path-to/video.mp4'
options.upload.title = videos[0]['title']
options.upload.description = '''This you can write description for video
That text written for example, you can write this what do you want :)'''
options.upload.tags = ['tags', 'writes', 'in a', 'taglist', 'add', 'some tags', 'this']
options.upload.preview = 'C:/path-to/thumbnails.jpg'
uploadVideo(session, options)
```
<h2 align="center"> -Upload video as premiere and access management- </h2>
```python
for video in videos:
options.upload.acess = 'PUBLIC' #is default | UNLISTED - Acess by link | PRIVATE - Restricted access | SCHEDULE - Planned release (not yet configurable)
options.upload.premiere = True
``` | ytty | /ytty-1.0.2.tar.gz/ytty-1.0.2/README.md | README.md |
===
ytu
===
.. image:: https://img.shields.io/pypi/v/ytu.svg
:target: https://pypi.python.org/pypi/ytu
.. image:: https://img.shields.io/travis/yaph/ytu.svg
:target: https://travis-ci.org/yaph/ytu
A library to extract information from YouTube URLs. Currently provides the function `video_id` to retrieve the video ID from a YouTube URL.
Usage
-----
::
import ytu
url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
if ytu.is_youtube(url):
print(ytu.video_id(url))
Credits
-------
This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.
.. _Cookiecutter: https://github.com/audreyr/cookiecutter
.. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage
| ytu | /ytu-0.2.0.tar.gz/ytu-0.2.0/README.rst | README.rst |
.. highlight:: shell
============
Contributing
============
Contributions are welcome, and they are greatly appreciated! Every little bit
helps, and credit will always be given.
You can contribute in many ways:
Types of Contributions
----------------------
Report Bugs
~~~~~~~~~~~
Report bugs at https://github.com/yaph/ytu/issues.
If you are reporting a bug, please include:
* Your operating system name and version.
* Any details about your local setup that might be helpful in troubleshooting.
* Detailed steps to reproduce the bug.
Fix Bugs
~~~~~~~~
Look through the GitHub issues for bugs. Anything tagged with "bug" and "help
wanted" is open to whoever wants to implement it.
Implement Features
~~~~~~~~~~~~~~~~~~
Look through the GitHub issues for features. Anything tagged with "enhancement"
and "help wanted" is open to whoever wants to implement it.
Write Documentation
~~~~~~~~~~~~~~~~~~~
ytu could always use more documentation, whether as part of the
official ytu docs, in docstrings, or even on the web in blog posts,
articles, and such.
Submit Feedback
~~~~~~~~~~~~~~~
The best way to send feedback is to file an issue at https://github.com/yaph/ytu/issues.
If you are proposing a feature:
* Explain in detail how it would work.
* Keep the scope as narrow as possible, to make it easier to implement.
* Remember that this is a volunteer-driven project, and that contributions
are welcome :)
Get Started!
------------
Ready to contribute? Here's how to set up `ytu` for local development.
1. Fork the `ytu` repo on GitHub.
2. Clone your fork locally::
$ git clone [email protected]:your_name_here/ytu.git
3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development::
$ mkvirtualenv ytu
$ cd ytu/
$ python setup.py develop
4. Create a branch for local development::
$ git checkout -b name-of-your-bugfix-or-feature
Now you can make your changes locally.
5. When you're done making changes, check that your changes pass flake8 and the
tests, including testing other Python versions with tox::
$ flake8 ytu tests
$ python setup.py test or py.test
$ tox
To get flake8 and tox, just pip install them into your virtualenv.
6. Commit your changes and push your branch to GitHub::
$ git add .
$ git commit -m "Your detailed description of your changes."
$ git push origin name-of-your-bugfix-or-feature
7. Submit a pull request through the GitHub website.
Pull Request Guidelines
-----------------------
Before you submit a pull request, check that it meets these guidelines:
1. The pull request should include tests.
2. If the pull request adds functionality, the docs should be updated. Put
your new functionality into a function with a docstring, and add the
feature to the list in README.rst.
3. The pull request should work for Python 3.5, 3.6 and 3.7, and for PyPy. Check
https://travis-ci.org/yaph/ytu/pull_requests
and make sure that the tests pass for all supported Python versions.
Tips
----
To run a subset of tests::
$ py.test tests.test_ytu | ytu | /ytu-0.2.0.tar.gz/ytu-0.2.0/CONTRIBUTING.rst | CONTRIBUTING.rst |
import os
import sys
from googleapiclient.discovery import build
import re
from datetime import datetime
import requests
import asyncio
import aiohttp
from fake_useragent import UserAgent
def compare_values(item_value: str, filter_value: str, filter_value_type: str) -> bool:
if filter_value_type == 'datetime':
item_value = datetime.strptime(re.findall('\d{4}-\d{2}-\d{2}', item_value)[0], '%Y-%m-%d')
filter_values = re.findall(r'\d{4}/\d{2}/\d{2}', filter_value)
if not bool(filter_values):
print(f'Invalid input data ({filter_value})')
sys.exit()
filter_values = [datetime.strptime(value.strip(), '%Y/%m/%d') for value in filter_values]
elif filter_value_type == 'int':
item_value = int(item_value)
filter_values = [int(value) for value in re.findall(r'\d+', filter_value)]
else:
print('Wrong parameter: filter_value_type in def compare_values()')
sys.exit()
if any(index == filter_value[0] for index in ['-', '+']):
index = True if filter_value[0] == '+' else False
if item_value >= filter_values[0]:
return index
else:
return not index
elif '-' in filter_value:
if not filter_values[0] <= item_value <= filter_values[1]:
return False
else:
return True
else:
print(f'Invalid input data! ({filter_value})')
sys.exit()
def statistics_filter(item_set: dict, filter_set: dict) -> bool:
for filter_key, filter_value in filter_set.items():
try:
if not compare_values(item_value=item_set[filter_key], filter_value=filter_value, filter_value_type='int'):
return False
except KeyError:
return False
return True
def snippet_filter(item_set: dict, filter_set: dict) -> bool:
for filter_key, filter_value in filter_set.items():
if filter_key == 'publishedAt':
if not compare_values(item_value=item_set[filter_key], filter_value=filter_value,
filter_value_type='datetime'):
return False
else:
if not any(check_type in filter_value for check_type in ['any:', 'all:']):
print(f'Invalid input data! ({filter_key})')
sys.exit()
functions = {
'all': all,
'any': any,
}
check_type = filter_value.split(':')[0].casefold().strip()
filter_values = [value.casefold().strip() for value in filter_value.split(':')[1].split(',')]
if filter_key == 'tags':
item_values = [item_value.casefold().strip() for item_value in item_set[filter_key]]
elif filter_key == 'title':
item_values = item_set['title'].casefold()
else:
print('Wrong filter key in snippet filter')
sys.exit()
if not functions[check_type](value in item_values for value in filter_values):
return False
return True
def run() -> dict:
filters = {
'snippet': {
'publishedAt': '',
'tags': '',
'title': ''
},
'statistics': {
'viewCount': '',
'likeCount': '',
'commentCount': '',
},
}
# Get input data
channel_url = input('Channel url: ')
for filter_category, filter_set in filters.items():
for filter_name in filter_set:
filters[filter_category][filter_name] = input(f'{filter_name}: ')
# Delete empty keys
for filter_category, filter_set in list(filters.items()):
for filter_name, filter_value in list(filter_set.items()):
if filter_value == '':
del filters[filter_category][filter_name]
if not bool(filters[filter_category]):
del filters[filter_category]
input_data = {'channel_url': channel_url, 'filters': filters}
return input_data
def main() -> None:
input_data = run()
path = 'yt_videos'
if not os.path.exists(path):
os.makedirs(path)
fake_user_agent = UserAgent()
headers = {'user-agent': fake_user_agent.random}
api_key = os.environ.get('YT_API_KEY')
youtube = build(serviceName='youtube', version='v3', developerKey=api_key)
filters = input_data['filters']
response = requests.get(input_data['channel_url'], headers=headers)
channel_id = re.findall(r'"externalId":".+","keywords"', response.text)[0].split('"')[3]
# Get playlist ID that contains all videos
request = youtube.channels().list(
part='contentDetails',
id=channel_id,
)
response = request.execute()
uploads_id = response['items'][0]['contentDetails']['relatedPlaylists']['uploads']
# Get video IDs
video_ids = []
next_page_token = None
while True:
request = youtube.playlistItems().list(
part='contentDetails',
playlistId=uploads_id,
maxResults=50,
pageToken=next_page_token,
)
response = request.execute()
for item in response['items']:
for key, value in item.items():
if key == 'contentDetails':
video_ids.append(value['videoId'])
if 'nextPageToken' not in response.keys():
del next_page_token
break
next_page_token = response['nextPageToken']
# Get info about videos
items = []
for i in range(0, len(video_ids), 50):
request = youtube.videos().list(
part=['snippet', 'statistics'],
id=video_ids[i: i+50],
maxResults=50
)
response = request.execute()
items.extend(response['items'])
# Get titles and urls of the filtered videos
video_titles = []
video_urls = []
for item in items:
for filter_category, filter_set in filters.items():
if not globals()[f'{filter_category}_filter'](item_set=item[filter_category], filter_set=filter_set):
break
else:
video_titles.append(item['snippet']['title'])
video_urls.append(f"http://youtube.com/watch?v={item['id']}")
# Get downloadable urls
download_urls = []
for video_title, video_url in zip(list(video_titles), video_urls):
response = requests.post('https://ssyoutube.com/api/convert', json={'url': video_url})
if response.status_code != 200:
video_titles.remove(video_title)
print(f"Can't download: {video_title}")
continue
tmp = ''
for item in response.json()['url']:
if item['type'] == 'mp4':
if item['quality'] == '720':
download_urls.append(item['url'])
break
elif item['quality'] == '360':
tmp = item['url']
else:
if bool(tmp):
download_urls.append(tmp)
else:
video_titles.remove(video_title)
print(f"Can't download: {video_title}")
# Download videos
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(download_videos(video_titles, download_urls, path=path))
def get_tasks(session, download_urls: list) -> list:
tasks = []
for url in download_urls:
tasks.append(session.get(url))
return tasks
async def download_videos(video_titles: list, download_urls: list, path: str):
async with aiohttp.ClientSession() as session:
# Make requests
tasks = get_tasks(session, download_urls)
responses = await asyncio.gather(*tasks)
# Save videos
for video_title, response in zip(video_titles, responses):
if response.status != 200:
print(f"Can't download: {video_title}")
continue
video_title = re.sub(f'[?,/:"*|<>]', '_', video_title).replace(f'{chr(92)}', '_')
with open(f'{path}/{video_title}.mp4', 'wb') as f:
while True:
chunk = await response.content.read()
if not chunk:
break
f.write(chunk)
print(fr'DOWNLOADED: {video_title}')
if __name__ == '__main__':
main() | ytube-video-downloader | /ytube_video_downloader-1.0.1-py3-none-any.whl/ytube_video_downloader/main.py | main.py |
|travis| |appveyor| |coveralls| |libraries|
.. |travis| image:: https://img.shields.io/travis/cdown/yturl/develop.svg?label=linux%20%2B%20mac%20tests
:target: https://travis-ci.org/cdown/yturl
:alt: Linux and Mac tests
.. |appveyor| image:: https://img.shields.io/appveyor/ci/cdown/yturl/develop.svg?label=windows%20tests
:target: https://ci.appveyor.com/project/cdown/yturl
:alt: Windows tests
.. |coveralls| image:: https://img.shields.io/coveralls/cdown/yturl/develop.svg?label=test%20coverage
:target: https://coveralls.io/github/cdown/yturl?branch=develop
:alt: Coverage
.. |libraries| image:: https://img.shields.io/librariesio/github/cdown/yturl.svg?label=dependencies
:target: https://libraries.io/github/cdown/yturl
:alt: Dependencies
yturl gets direct media URLs to YouTube media, freeing you having to
view them in your browser.
yturl is still maintained, but is pretty much "done". Outside of changes to
match YouTube API changes, bug fixes, and support for newer Python versions,
development is complete.
Usage
-----
By default, yturl prints the media URL to standard output.
::
$ yturl 'http://www.youtube.com/watch?v=8TCxE0bWQeQ'
Using itag 43.
http://r2---sn-uphxqvujvh-30al.googlevideo.com/videoplayback?source=[...]
You can use this URL in the media player of your choice. For media players that
can be launched from the command line, this typically means that you can do
something like the following to watch it in your preferred player:
::
$ <your-preferred-player> "$(yturl 'http://www.youtube.com/watch?v=8TCxE0bWQeQ')"
There is also a ``-q`` option for controlling the quality (for example ``-q
high``), see :code:`yturl --help` for more information.
Installation
------------
To install the latest stable version from PyPi:
.. code::
$ pip install -U yturl
To install the latest development version directly from GitHub:
.. code::
$ pip install -U git+https://github.com/cdown/yturl.git@develop
Testing
-------
.. code::
$ pip install tox
$ tox
..........
----------------------------------------------------------------------
Ran 10 tests in 4.088s
OK
| yturl | /yturl-2.0.2.tar.gz/yturl-2.0.2/README.rst | README.rst |
from __future__ import print_function, unicode_literals
import argparse
import collections
import logging
import sys
import requests
from six import iteritems, iterkeys
from six.moves.urllib.parse import parse_qs, urlencode, urlparse, urlunparse
log = logging.getLogger(__name__)
# A mapping of quality names to functions that determine the desired itag from
# a list of itags. This is used when `-q quality` is passed on the command line
# to determine which available itag best suits that quality specification.
NAMED_QUALITY_GROUPS = {
'low': lambda itags: itags[-1],
'medium': lambda itags: itags[len(itags) // 2],
'high': lambda itags: itags[0],
}
DEFAULT_HEADERS = {
'User-Agent': 'yturl (https://github.com/cdown/yturl)',
}
def construct_youtube_get_video_info_url(video_id):
'''
Construct a YouTube API url for the get_video_id endpoint from a video ID.
'''
base_parsed_api_url = urlparse('https://www.youtube.com/get_video_info')
new_query = urlencode({'video_id': video_id})
# As documented in the core Python docs, ._replace() is not internal, the
# leading underscore is just to prevent name collisions with field names.
new_parsed_api_url = base_parsed_api_url._replace(query=new_query)
new_api_url = urlunparse(new_parsed_api_url)
return new_api_url
def video_id_from_url(url):
'''
Parse a video ID, either from the "v" parameter or the last URL path slice.
'''
parsed_url = urlparse(url)
url_params = parse_qs_single(parsed_url.query)
video_id = url_params.get('v', parsed_url.path.split('/')[-1])
log.debug('Parsed video ID %s from %s', url, video_id)
return video_id
def itags_for_video(video_id):
'''
Return itags for a video with their media URLs, sorted by quality.
'''
api_url = construct_youtube_get_video_info_url(video_id)
api_response_raw = requests.get(api_url, headers=DEFAULT_HEADERS)
log.debug('Raw API response: %r', api_response_raw.text)
api_response = parse_qs_single(api_response_raw.text)
log.debug('parse_qs_single API response: %r', api_response)
if api_response.get('status') != 'ok':
reason = api_response.get('reason', 'Unspecified error.')
# Unfortunately YouTube returns HTML in this instance, so there's no
# reasonable way to use api_response directly.
if 'CAPTCHA' in api_response_raw.text:
reason = 'You need to solve a CAPTCHA, visit %s' % api_url
raise YouTubeAPIError(reason)
# The YouTube API returns these from highest to lowest quality, which we
# rely on. From this point forward, we need to make sure we maintain order.
streams = api_response['url_encoded_fmt_stream_map'].split(',')
videos = [parse_qs_single(stream) for stream in streams]
return collections.OrderedDict((vid['itag'], vid['url']) for vid in videos)
def itag_from_quality(group_or_itag, itags):
'''
If "group_or_itag" is a quality group, return an appropriate itag from
itags for that group. Otherwise, group_or_itag is an itag -- just return
it.
'''
if group_or_itag in NAMED_QUALITY_GROUPS:
# "group_or_itag" is really a named quality group. Use
# NAMED_QUALITY_GROUPS to get a function to determine the itag to use.
func_to_get_desired_itag = NAMED_QUALITY_GROUPS[group_or_itag]
return func_to_get_desired_itag(itags)
elif group_or_itag in itags:
# "group_or_itag" is really an itag. Just pass it through unaltered.
return group_or_itag
else:
raise ValueError(
'Group/itag %s unavailable (video itags: %r, known groups: %r)' % (
group_or_itag, itags, list(NAMED_QUALITY_GROUPS),
)
)
def parse_qs_single(query_string):
'''
Parse a query string per parse_qs, but with the values as single elements.
parse_qs, as mandated by the standard, dutifully returns each value as a
list in case the key appears twice in the input, which can be quite
inconvienient and results in hard to read code.
We *could* just do dict(parse_qsl(x)), but this would indiscriminately
discard any duplicates, and we'd rather raise an exception on that.
Instead, we verify that no key appears twice (throwing an exception if any
do), and then return each value as a single element in the dictionary.
'''
raw_pairs = parse_qs(query_string)
dupes = [key for (key, values) in iteritems(raw_pairs) if len(values) > 1]
if dupes:
raise ValueError('Duplicate keys in query string: %r' % dupes)
one_val_pairs = {key: values[0] for (key, values) in iteritems(raw_pairs)}
return one_val_pairs
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'-q', '--quality', default='medium', help='low/medium/high or an itag',
)
parser.add_argument(
'--debug',
action="store_const", dest='log_level',
const=logging.DEBUG, default=logging.WARNING,
help='enable debug logging',
)
parser.add_argument(
'video_id', metavar='video_id/url', type=video_id_from_url,
)
args = parser.parse_args(argv)
logging.basicConfig(level=args.log_level)
itag_to_url_map = itags_for_video(args.video_id)
# available_itags must be indexable for use with NAMED_QUALITY_GROUPS
available_itags = list(iterkeys(itag_to_url_map))
desired_itag = itag_from_quality(args.quality, available_itags)
print('Using itag %s.' % desired_itag, file=sys.stderr)
print(itag_to_url_map[desired_itag])
class YouTubeAPIError(Exception):
'''
Raised when the YouTube API returns failure. This is not used when issues
arise during processing of the received API data -- in those cases, we use
more specific exception types.
'''
pass
if __name__ == '__main__':
main() | yturl | /yturl-2.0.2.tar.gz/yturl-2.0.2/yturl.py | yturl.py |
# ytutils
YouTube video & channel details extractor
## Pypi Website
- [ytutils](https://pypi.org/project/ytutils)
## Features
- Extract video details
- Extract channel details
## Installation
```bash
pip install ytutils
```
## Video Extraction
### Importing
```python
from ytutils.Video import Video
```
### Step-1
```python
api_key = "YOUR API KEY"
vid = Video(api_key)
```
### Step-2
```python
try:
vid.start(video_url="https://www.youtube.com/watch?v=hW7qJZK2UAc") # Or vid.start(video_id="hW7qJZK2UAc")
except:
pass # Error occurred
```
### Step-3
```python
details = vid.result()
print(details['title'])
```
## Channel Extraction
### Importing
```python
from ytuils.Channel import Channel
```
### Step-1
```python
api_key = "YOUR API KEY"
cha = Channel(api_key)
```
### Step-2
```python
try:
cha.start(channel_url="https://www.youtube.com/channel/UC_yAFedtY2po4noljIqSM1w") # Or cha.start(channel_id="UC_yAFedtY2po4noljIqSM1w")
except:
pass # Error Occurred
```
### Step-3
```python
details = cha.result()
print(details['title'])
```
## Contact me
- [Twitter](https://twitter.com/SanjayDevTech)
| ytutils | /ytutils-0.1.0.4.tar.gz/ytutils-0.1.0.4/README.md | README.md |
## 部署准备(server & client)
### clone代码
```
git clone https://github.com/cao19881125/ytvpn.git
```
### build镜像
```
cd ytvpn
docker build -t cao19881125/ytvpn:latest docker/
```
### 创建配置文件
```
mkdir /etc/ytvpn
cp etc/* /etc/ytvpn/
```
## server部署
### 开启转发
#### 关闭selinux
```
sed -i 's/SELINUX.*=.*enforcing/SELINUX=disabled/g' /etc/selinux/config
reboot
```
#### 开启转发
```
# vim /etc/sysctl.conf
net.ipv4.ip_forward = 1
sysctl -p
```
#### 配置snat
```
iptables -A POSTROUTING -t nat -o eth0 -j MASQUERADE
```
### 修改配置文件
```
# vim /etc/ytvpn/server.cfg
[DEFAULT]
LISTEN_PORT:9999
LOG_LEVEL=DEBUG
BANDWIDTH=100
CLIENT_TO_CLIENT=False
SERVERIP=10.5.0.1
DHCP_POOL=10.5.0.10-20
user_file=/etc/ytvpn/user_file
```
需要注意的参数如下(可以用默认值):
- LISTEN_PORT:服务端监听的端口
- SERVERIP:启动后服务端使用的IP
- DHCP_POOL:分配给客户端的IP
```
# vim /etc/ytvpn/user_file
[USER]
test=123456
```
- 配置用户名密码
### 启动
```
docker run -t -d --name "ytvpn-server" --network host -v /etc/ytvpn/:/etc/ytvpn/ -v /var/log/ytvpn/:/var/log/ytvpn/ --restart always --privileged cao19881125/ytvpn:latest ytvpn --run_type server --config-file /etc/ytvpn/server.cfg
```
## client部署
### 修改配置文件
```
# vim /etc/ytvpn/client.cfg
[DEFAULT]
SERVER_IP=192.168.184.139
SERVER_PORT=9999
LOG_LEVEL=DEBUG
USER_NAME=test
PASSWORD=123456
```
- SERVER_IP:服务端的IP
- SERVER_PORT:服务端监听的端口
- USER_NAME:用户名
- PASSWORD:密码
### 运行
```
docker run -t -d --name "ytvpn-client" --network host -v /etc/ytvpn/:/etc/ytvpn/ -v /var/log/ytvpn/:/var/log/ytvpn/ --restart always --privileged cao19881125/ytvpn:latest ytvpn --run_type client --config-file /etc/ytvpn/client.cfg
```
| ytvpn | /ytvpn-1.0.0.tar.gz/ytvpn-1.0.0/README.md | README.md |
# yahoo-tv-search
## Overview
- A simple tv program api by scraping [Yahoo Japan 番組表](https://tv.yahoo.co.jp/listings/realtime/).
- Search tv programs using
- keyword
- broad types (ex. BS, CS, terrestrial)
- prefecture
## Sample
### Source code
See `example` directory.
```python
from ytvsearch.searcher import Searcher
from ytvsearch.search_option import SearchOption
tv_searcher = Searcher()
tv_programs = tv_searcher.run(
keyword='北海道',
broad_types=[ SearchOption.Broadcast.TERRESTRIAL ],
fetch_limit=10
)
for tv_program in tv_programs:
print('{date}: {title} ({channel})'.format(
date=tv_program.date['start'],
title=tv_program.title,
channel=tv_program.channel
))
```
### Output
```text
2020-04-25 21:00:00+09:00: NHKスペシャル▽新型コロナウイルス どうなる緊急事態宣言~医療と経済の行方~ (NHK総合1・東京(地上波))
2020-04-26 04:30:00+09:00: イッピン・選「個性が光る 北の大地の器~北海道 札幌の焼き物~」 (NHK総合1・東京(地上波))
2020-04-26 07:45:00+09:00: さわやか自然百景「早春 北海道 石狩湾」 (NHK総合1・東京(地上波))
2020-04-26 13:35:00+09:00: ニッポンの里山 ふるさとの絶景に出会う旅「シマエナガ舞う北国の森 北海道占冠村」 (NHK総合1・東京(地上波))
2020-04-27 11:00:00+09:00: 韓国ドラマ「ラブレイン」 ★第19話「ねじれた運命」 (TOKYO MX1(地上波))
2020-04-28 01:28:00+09:00: 週刊EXILE まだまだあった三代目JSB10か月長期密着未公開SP!裏話も! (TBS1(地上波))
2020-04-28 11:00:00+09:00: 韓国ドラマ「ラブレイン」 ★第20話「愛の誓い」 (TOKYO MX1(地上波))
2020-04-29 09:00:00+09:00: 小さな旅 選「特集 山の歌 総集編」 (NHK総合1・東京(地上波))
2020-04-30 00:15:00+09:00: NHKスペシャル▽新型コロナウイルス どうなる緊急事態宣言~医療と経済の行方 (NHK総合1・東京(地上波))
2020-04-30 02:35:00+09:00: 日本夜景めぐり「北海道」 (NHK総合1・東京(地上波))
```
## License
MIT
| ytvsearch | /ytvsearch-0.2.tar.gz/ytvsearch-0.2/README.md | README.md |
from threading import Thread
import time
import click
import yt_dlp
from loguru import logger
import os
from src.whisper.subtitles import write_srt
from src.whisper.transcribe import initialize_whisper_model
from src.youtube.download import download, download_audio
@click.command()
@click.option("--url", "-u", required=True, help="Youtube URL.")
@click.option("--threads", "-n", default=8, help="Number of threads to use.")
@click.option(
"--format",
"-f",
default="bestvideo+bestaudio/best",
help="Download format. See: https://github.com/yt-dlp/yt-dlp#format-selection-examples",
)
@click.option(
"--translate",
"-t",
is_flag=True,
default=False,
help="Translate the subtitles to English.",
)
@click.option(
"--model_name",
"-m",
default="tiny.en",
help="Name of the model to use. e.g. (tiny, tiny.en, base, base.en, small, small.en,\
medium, medium.en, large-v1, or large-v2), recommended: (large-v2)",
)
@click.option(
"--model_root",
"-r",
default=None,
help="Root directory for the models.",
)
@click.option(
"--cpu",
is_flag=True,
default=False,
help="Use CPU instead of GPU. This is useful if you do not have a GPU.",
)
@click.option(
"--srt_only",
"-s",
is_flag=True,
default=False,
help="Only generate subtitles. Do not download video.",
)
@click.option(
"--video_only",
"-v",
is_flag=True,
default=False,
help="Only download video. Do not generate subtitles.",
)
def main(
url: str,
threads: int,
format: str,
translate: bool,
model_name: str,
model_root: str | None,
cpu: bool,
srt_only: bool,
video_only: bool,
) -> None:
"""Download video from Youtube and generate subtitles."""
# Check if URL is valid
try:
yt_dlp.YoutubeDL().extract_info(
url, download=False
) # This will throw exception if URL is not valid.
except Exception:
click.echo("Invalid URL. Please provide a valid YouTube URL.")
return
# Download video in parallel
download_thread = None
if not srt_only:
# Download video in parallel
download_thread = Thread(target=download, args=(url, threads, format))
download_thread.start()
else:
logger.info("Skipping video download due to --srt_only flag.")
# Transcribe audio
logger.info(f"Downloading video from {url}.")
if not video_only:
audio_file_name = download_audio(url, threads)
srt_file_name = audio_file_name.split(".")[0] + ".srt"
if not os.path.exists(srt_file_name):
logger.info(f"Transcribing audio from {audio_file_name}.")
model = initialize_whisper_model(
model_name=model_name, model_root=model_root, cpu=cpu
)
logger.info("Model initialized successfully.")
begin_transcription = time.time()
segs, info = model.transcribe(
audio=audio_file_name,
vad_filter=True,
task="transcribe" if not translate else "translate",
)
write_srt(segments=segs, file=srt_file_name)
logger.info(
f"Transcription completed in {time.time() - begin_transcription:.2f} \
seconds. Audio duration: {info.duration:.2f} seconds."
)
if os.path.exists(audio_file_name):
os.remove(audio_file_name)
else:
logger.info(
f"Skipping audio transcription due to {srt_file_name} already exists."
)
else:
logger.info("Skipping audio transcription due to --video_only flag.")
if download_thread is not None:
download_thread.join()
if __name__ == "__main__":
main() | ytws | /ytws-0.2.1-py3-none-any.whl/src/cli/main.py | main.py |
import sys
import argparse
import logging
from common.variables import DEFAULT_PORT
from common.decos import log
from server.server_database import ServerDB
import threading
import os
from PyQt5.QtWidgets import QApplication, QMessageBox
from PyQt5.QtCore import QTimer
from server.server_gui import MainWindow, gui_create_model, HistoryWindow, create_stat_model, ConfigWindow
import configparser # https://docs.python.org/3/library/configparser.html
from server.core import Server
# Инициализация логирования сервера.
LOGGER = logging.getLogger('server')
# Флаг, что был подключён новый пользователь, нужен чтобы не нагружать BD
# постоянными запросами на обновление
new_connection = False
conflag_lock = threading.Lock()
# Парсер аргументов командной строки.
@log
def arg_parser(default_port, default_address):
"""
Парсер аргументов командной строки
:param default_port:
:param default_address:
:return:
"""
LOGGER.debug(f'Инициализация парсера аргументов командной строки: {sys.argv}')
parser = argparse.ArgumentParser()
parser.add_argument('-p', default=default_port, type=int, nargs='?')
parser.add_argument('-a', default=default_address, nargs='?')
parser.add_argument('--no_gui', action='store_true')
namespace = parser.parse_args(sys.argv[1:])
listen_address = namespace.a
listen_port = namespace.p
gui_flag = namespace.no_gui
LOGGER.debug('Аргументы успешно загружены.')
return listen_address, listen_port, gui_flag
def main():
# Загрузка файла конфигурации сервера
config = configparser.ConfigParser()
dir_path = os.path.dirname(os.path.realpath(__file__))
config.read(f"{dir_path}server/{'server.ini'}")
# Если конфиг файл загружен правильно, запускаемся, иначе конфиг по умолчанию.
if 'SETTINGS' not in config:
config.add_section('SETTINGS')
config.set('SETTINGS', 'Default_port', str(DEFAULT_PORT))
config.set('SETTINGS', 'Listen_Address', '')
config.set('SETTINGS', 'Database_path', '')
config.set('SETTINGS', 'Database_file', 'server/server_database.db3')
# Загрузка параметров командной строки, если нет параметров, то задаём значения по умолчанию
listen_address, listen_port, gui_flag = arg_parser(
config['SETTINGS']['Default_port'], config['SETTINGS']['Listen_Address'])
# Инициализация базы данных
# database = ServerDB()
database = ServerDB(
os.path.join(
config['SETTINGS']['Database_path'],
config['SETTINGS']['Database_file']))
# Создание экземпляра класса - сервера, подключение к БД, запуск
server = Server(listen_address, listen_port, database)
# server.main_loop()
server.daemon = True
server.start()
# Создаём графическое окружение для сервера:
server_app = QApplication(sys.argv)
main_window = MainWindow(database, server, config)
# Инициализируем параметры в окна
main_window.statusBar().showMessage('Server Working')
main_window.active_clients_table.setModel(gui_create_model(database))
main_window.active_clients_table.resizeColumnsToContents()
main_window.active_clients_table.resizeRowsToContents()
def list_update():
"""
Функция, обновляющая список подключённых, проверяет флаг подключения, и
если надо обновляет список.
:return:
"""
# global new_connection
# if new_connection:
# main_window.active_clients_table.setModel(
# gui_create_model(database))
# main_window.active_clients_table.resizeColumnsToContents()
# main_window.active_clients_table.resizeRowsToContents()
# with conflag_lock:
# new_connection = False
main_window.active_clients_table.setModel(
gui_create_model(database))
main_window.active_clients_table.resizeColumnsToContents()
main_window.active_clients_table.resizeRowsToContents()
def show_statistics():
"""
Функция, создающая окно со статистикой клиентов.
:return:
"""
global stat_window
stat_window = HistoryWindow()
stat_window.history_table.setModel(create_stat_model(database))
stat_window.history_table.resizeColumnsToContents()
stat_window.history_table.resizeRowsToContents()
stat_window.show()
def server_config():
"""
Функция создающая окно с настройками сервера.
:return:
"""
global config_window
# Создаём окно и заносим в него текущие параметры
config_window = ConfigWindow()
config_window.db_path.insert(config['SETTINGS']['Database_path'])
config_window.db_file.insert(config['SETTINGS']['Database_file'])
config_window.port.insert(config['SETTINGS']['Default_port'])
config_window.ip.insert(config['SETTINGS']['Listen_Address'])
config_window.save_btn.clicked.connect(save_server_config)
def save_server_config():
"""
Функция сохранения настроек.
:return:
"""
global config_window
message = QMessageBox()
config['SETTINGS']['Database_path'] = config_window.db_path.text()
config['SETTINGS']['Database_file'] = config_window.db_file.text()
try:
port = int(config_window.port.text())
except ValueError:
message.warning(config_window, 'Ошибка', 'Порт должен быть числом')
else:
config['SETTINGS']['Listen_Address'] = config_window.ip.text()
if 1023 < port < 65536:
config['SETTINGS']['Default_port'] = str(port)
print(port)
with open('server/server.ini', 'w') as conf:
config.write(conf)
message.information(
config_window, 'OK', 'Настройки успешно сохранены!')
else:
message.warning(
config_window,
'Ошибка',
'Порт должен быть от 1024 до 65536')
# Таймер, обновляющий список клиентов 1 раз в секунду
timer = QTimer()
timer.timeout.connect(list_update)
timer.start(1000)
# Связываем кнопки с процедурами
main_window.refresh_button.triggered.connect(list_update)
main_window.show_history_button.triggered.connect(show_statistics)
main_window.config_btn.triggered.connect(server_config)
# Запускаем GUI
server_app.exec_()
if __name__ == '__main__':
main() | yu-messenger-server | /yu_messenger_server-0.0.3-py3-none-any.whl/server/server_start.py | server_start.py |
from PyQt5.QtWidgets import QDialog, QLabel, QComboBox, QPushButton, \
QApplication
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QStandardItemModel, QStandardItem
class DelUserDialog(QDialog):
"""
Класс - диалог выбора контакта для удаления.
"""
def __init__(self, database, server):
super().__init__()
self.database = database
self.server = server
self.setFixedSize(350, 120)
self.setWindowTitle('Удаление пользователя c сервера')
self.setAttribute(Qt.WA_DeleteOnClose)
self.setModal(True)
self.selector_label = QLabel(
'Выберите пользователя для удаления:', self)
self.selector_label.setFixedSize(280, 20)
self.selector_label.move(10, 0)
self.selector = QComboBox(self)
self.selector.setFixedSize(200, 20)
self.selector.move(10, 30)
self.btn_ok = QPushButton('Удалить', self)
self.btn_ok.setFixedSize(100, 25)
self.btn_ok.move(230, 30)
self.btn_ok.clicked.connect(self.remove_user)
self.btn_cancel = QPushButton('Отмена', self)
self.btn_cancel.setFixedSize(100, 25)
self.btn_cancel.move(230, 70)
self.btn_cancel.clicked.connect(self.close)
self.all_users_fill()
def all_users_fill(self):
"""
Метод заполняющий список пользователей.
:return:
"""
self.selector.addItems([item[0]
for item in self.database.users_list()])
def remove_user(self):
"""
Метод - обработчик удаления пользователя.
:return:
"""
self.database.remove_user(self.selector.currentText())
if self.selector.currentText() in self.server.names:
sock = self.server.names[self.selector.currentText()]
del self.server.names[self.selector.currentText()]
self.server.remove_client(sock)
# Рассылаем клиентам сообщение о необходимости обновить справочники
self.server.service_update_lists()
self.close()
if __name__ == '__main__':
app = QApplication([])
from server_database import ServerDB
database = ServerDB('../client/server_database.db3')
import os
import sys
path1 = os.path.join(os.getcwd(), '..')
sys.path.insert(0, path1)
from core import Server
server = Server('127.0.0.1', 7777, database)
dial = DelUserDialog(database, server)
dial.show()
app.exec_() | yu-messenger-server | /yu_messenger_server-0.0.3-py3-none-any.whl/server/server/remove_user.py | remove_user.py |
import binascii
import hmac
import json
import os
import sys
import threading
import logging
import socket
import select
sys.path.append('../')
from common.metaclasses import ServerVerifier
from common.descrptrs import Port
from common.variables import ACTION, TIME, \
USER, ACCOUNT_NAME, SENDER, PRESENCE, ERROR, MESSAGE, \
MESSAGE_TEXT, RESPONSE_400, DESTINATION, RESPONSE_200, EXIT, \
GET_CONTACTS, RESPONSE_202, LIST_INFO, ADD_CONTACT, REMOVE_CONTACT, \
USERS_REQUEST, RESPONSE_511, DATA, RESPONSE, PUBLIC_KEY, \
MAX_CONNECTIONS, PUBLIC_KEY_REQUEST, RESPONSE_205
from common.utils import get_message, send_message
# from common.decos import login_required
# Флаг, что был подключён новый пользователь, нужен чтобы не нагружать BD
# постоянными запросами на обновление
new_connection = False
conflag_lock = threading.Lock()
# Инициализация логирования сервера.
LOGGER = logging.getLogger('server')
class Server(threading.Thread, metaclass=ServerVerifier):
port = Port()
"""
Основной класс сервера. Принимает соединения, словари - пакеты
от клиентов, обрабатывает поступающие сообщения.
Работает в качестве отдельного потока.
"""
def __init__(self, listen_address, listen_port, database):
# Параметры подключения
self.addr = listen_address
self.port = listen_port
# Список подключённых клиентов.
self.clients = []
# Список сообщений на отправку.
self.messages = []
# Словарь содержащий сопоставленные имена и соответствующие им сокеты.
self.names = dict()
# База данных сервера
self.database = database
# Сокет, через который будет осуществляться работа
self.sock = None
# Сокеты
self.listen_sockets = None
self.error_sockets = None
# Флаг продолжения работы
self.running = True
# # Конструктор предка
super().__init__()
def process_client_message(self, message, client):
"""
Обработчик сообщений от клиентов, принимает словарь - сообщение от клиента,
проверяет корректность, отправляет словарь-ответ в случае необходимости.
:param message:
:param client:
"""
global new_connection
LOGGER.debug(f'Разбор сообщения от клиента : {message}')
# Если это сообщение о присутствии, принимаем и отвечаем
if ACTION in message \
and message[ACTION] == PRESENCE \
and TIME in message \
and USER in message:
# Если сообщение о присутствии, то вызываем функцию авторизации.
self.autorize_user(message, client)
# Если это сообщение, то добавляем его в очередь сообщений.
# Ответ не требуется.
elif ACTION in message \
and message[ACTION] == MESSAGE \
and DESTINATION in message \
and TIME in message \
and SENDER in message \
and MESSAGE_TEXT in message \
and self.names[message[SENDER]] == client:
if message[DESTINATION] in self.names:
self.messages.append(message)
self.database.process_message(message[SENDER], message[DESTINATION])
try:
send_message(client, RESPONSE_200)
except OSError:
self.remove_client(client)
else:
response = RESPONSE_400
response[ERROR] = 'Пользователь не зарегистрирован на сервере.'
try:
send_message(client, response)
except OSError:
pass
return
# Если клиент выходит
elif ACTION in message \
and message[ACTION] == EXIT \
and ACCOUNT_NAME in message \
and self.names[message[ACCOUNT_NAME]] == client:
# удаляем пользователя из таблицы активных пользователей
self.remove_client(client)
# Если это запрос контакт-листа
elif ACTION in message \
and message[ACTION] == GET_CONTACTS \
and USER in message \
and self.names[message[USER]] == client:
response = RESPONSE_202
response[LIST_INFO] = self.database.get_contacts(message[USER])
try:
send_message(client, response)
except OSError:
self.remove_client(client)
# Если это добавление контакта
elif ACTION in message \
and message[ACTION] == ADD_CONTACT \
and ACCOUNT_NAME in message \
and USER in message \
and self.names[message[USER]] == client:
self.database.add_contact(message[USER], message[ACCOUNT_NAME])
try:
send_message(client, RESPONSE_200)
except OSError:
self.remove_client(client)
# Если это удаление контакта
elif ACTION in message \
and message[ACTION] == REMOVE_CONTACT \
and ACCOUNT_NAME in message \
and USER in message \
and self.names[message[USER]] == client:
self.database.remove_contact(message[USER], message[ACCOUNT_NAME])
try:
send_message(client, RESPONSE_200)
except OSError:
self.remove_client(client)
# Если это запрос известных пользователей
elif ACTION in message \
and message[ACTION] == USERS_REQUEST \
and ACCOUNT_NAME in message \
and self.names[message[ACCOUNT_NAME]] == client:
response = RESPONSE_202
response[LIST_INFO] = [user[0] for user in self.database.users_list()]
try:
send_message(client, response)
except OSError:
self.remove_client(client)
# Если это запрос публичного ключа пользователя
elif ACTION in message \
and message[ACTION] == PUBLIC_KEY_REQUEST \
and ACCOUNT_NAME in message:
response = RESPONSE_511
response[DATA] = self.database.get_pubkey(message[ACCOUNT_NAME])
# может быть, что ключа ещё нет (пользователь никогда не логинился,
# тогда шлём 400)
if response[DATA]:
try:
send_message(client, response)
except OSError:
self.remove_client(client)
else:
response = RESPONSE_400
response[ERROR] = 'Нет публичного ключа для данного пользователя'
try:
send_message(client, response)
except OSError:
self.remove_client(client)
# Иначе отдаём Bad request
else:
response = RESPONSE_400
response[ERROR] = 'Запрос некорректен.'
try:
send_message(client, response)
except OSError:
self.remove_client(client)
return
def autorize_user(self, message, sock):
"""
Метод реализующий авторизацию пользователей.
:param message:
:param sock:
:return:
"""
# Если имя пользователя уже занято, то возвращаем 400
LOGGER.debug(f'Start auth process for {message[USER]}')
if message[USER][ACCOUNT_NAME] in self.names.keys():
response = RESPONSE_400
response[ERROR] = 'Имя пользователя уже занято.'
try:
LOGGER.debug(f'Username busy, sending {response}')
send_message(sock, response)
except OSError:
LOGGER.debug('OS Error')
pass
self.clients.remove(sock)
sock.close()
# Проверяем что пользователь зарегистрирован на сервере.
elif not self.database.check_user(message[USER][ACCOUNT_NAME]):
response = RESPONSE_400
response[ERROR] = 'Пользователь не зарегистрирован.'
try:
LOGGER.debug(f'Unknown username, sending {response}')
send_message(sock, response)
except OSError:
pass
self.clients.remove(sock)
sock.close()
else:
LOGGER.debug('Correct username, starting passwd check.')
# Иначе отвечаем 511 и проводим процедуру авторизации
# Словарь - заготовка
message_auth = RESPONSE_511
# Набор байтов в hex представлении
random_str = binascii.hexlify(os.urandom(64))
# В словарь байты нельзя, декодируем (json.dumps -> TypeError)
message_auth[DATA] = random_str.decode('ascii')
# Создаём хэш пароля и связки со случайной строкой,
# сохраняем серверную версию ключа
server_hash = hmac.new(self.database.get_hash(message[USER][ACCOUNT_NAME]), random_str, 'MD5')
digest = server_hash.digest()
LOGGER.debug(f'Auth message = {message_auth}')
try:
# Обмен с клиентом
send_message(sock, message_auth)
ans = get_message(sock)
except OSError as err:
LOGGER.debug('Error in auth, data:', exc_info=err)
sock.close()
return
client_digest = binascii.a2b_base64(ans[DATA])
# Если ответ клиента корректный, то сохраняем его в список пользователей.
if RESPONSE in ans \
and ans[RESPONSE] == 511 \
and hmac.compare_digest(digest, client_digest):
self.names[message[USER][ACCOUNT_NAME]] = sock
client_ip, client_port = sock.getpeername()
try:
send_message(sock, RESPONSE_200)
except OSError:
self.remove_client(message[USER][ACCOUNT_NAME])
# добавляем пользователя в список активных и,
# если у него изменился открытый ключ, то сохраняем новый
self.database.user_login(
message[USER][ACCOUNT_NAME],
client_ip,
client_port,
message[USER][PUBLIC_KEY])
else:
response = RESPONSE_400
response[ERROR] = 'Неверный пароль.'
try:
send_message(sock, response)
except OSError:
pass
self.clients.remove(sock)
sock.close()
def remove_client(self, client):
"""
Метод обработчик клиента с которым прервана связь.
Ищет клиента и удаляет его из списков и базы.
:param self:
:param client:
:return:
"""
LOGGER.info(f'Клиент {client.getpeername()} отключился от сервера.')
for name in self.names:
if self.names[name] == client:
self.database.user_logout(name)
del self.names[name]
break
self.clients.remove(client)
client.close()
def process_message(self, message, listen_socks):
"""
Функция адресной отправки сообщения определённому клиенту. Принимает словарь сообщение,
список зарегистрированных пользователей и слушающие сокеты. Ничего не возвращает.
:param message:
:param listen_socks:
:return:
"""
if message[DESTINATION] in self.names \
and self.names[message[DESTINATION]] in listen_socks:
try:
send_message(self.names[message[DESTINATION]], message)
LOGGER.info(f'Отправлено сообщение пользователю {message[DESTINATION]} '
f'от пользователя {message[SENDER]}.')
except OSError:
self.remove_client(message[DESTINATION])
elif message[DESTINATION] in self.names and self.names[message[DESTINATION]] not in listen_socks:
raise ConnectionError
else:
LOGGER.error(
f'Пользователь {message[DESTINATION]} не зарегистрирован на сервере, '
f'отправка сообщения невозможна.')
def init_socket(self):
"""
Метод инициализатор сокета.
:return:
"""
LOGGER.info(
f'Запущен сервер, порт для подключений: {self.port}, '
f'адрес с которого принимаются подключения: {self.addr}. '
f'Если адрес не указан, принимаются соединения с любых адресов.')
# Готовим сокет
transport = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
transport.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
transport.bind((self.addr, self.port))
transport.settimeout(0.5)
# Начинаем слушать сокет
self.sock = transport
self.sock.listen()
self.sock.listen(MAX_CONNECTIONS)
def run(self):
"""
Основной цкл потока.
:return:
"""
global new_connection
# Инициализация Сокета
self.init_socket()
# Основной цикл программы сервера
while True:
# Ждём подключения, если таймаут вышел, ловим исключение.
try:
client, client_address = self.sock.accept()
except OSError:
pass
else:
LOGGER.info(f'Установлено соединение с ПК {client_address}')
client.settimeout(3)
self.clients.append(client)
recv_data_lst = []
send_data_lst = []
# err_lst = []
# Проверяем на наличие ждущих клиентов
try:
if self.clients:
recv_data_lst, send_data_lst, err_lst = select.select(self.clients, self.clients, [], 0)
except OSError as err:
LOGGER.error(f'Ошибка работы с сокетами: {err}')
# принимаем сообщения и если ошибка, исключаем клиента.
if recv_data_lst:
for client_with_message in recv_data_lst:
try:
self.process_client_message(get_message(client_with_message),
client_with_message)
except (OSError, json.JSONDecodeError, TypeError) as err:
LOGGER.debug(f'Getting data from client exception.', exc_info=err)
self.remove_client(client_with_message)
# Если есть сообщения, обрабатываем каждое.
for i in self.messages:
try:
self.process_message(i, send_data_lst)
except(ConnectionAbortedError, ConnectionError, ConnectionResetError, ConnectionRefusedError):
LOGGER.info(f'Связь с клиентом с именем {i[DESTINATION]} была потеряна')
self.clients.remove(self.names[i[DESTINATION]])
self.database.user_logout(i[DESTINATION])
del self.names[i[DESTINATION]]
with conflag_lock:
new_connection = True
self.messages.clear()
def service_update_lists(self):
"""
Метод реализующий отправку сервисного сообщения 205 клиентам.
:return:
"""
for client in self.names:
try:
send_message(self.names[client], RESPONSE_205)
except OSError:
self.remove_client(self.names[client]) | yu-messenger-server | /yu_messenger_server-0.0.3-py3-none-any.whl/server/server/core.py | core.py |
from PyQt5.QtWidgets import QDialog, QPushButton, QLineEdit, \
QApplication, QLabel, QMessageBox
from PyQt5.QtCore import Qt
import hashlib
import binascii
class RegisterUser(QDialog):
""" Класс диалог регистрации пользователя на сервере. """
def __init__(self, database, server):
super().__init__()
self.database = database
self.server = server
self.setWindowTitle('Регистрация')
self.setFixedSize(220, 183)
self.setModal(True)
self.setAttribute(Qt.WA_DeleteOnClose)
self.label_username = QLabel('Введите имя пользователя:', self)
self.label_username.move(10, 10)
self.label_username.setFixedSize(200, 15)
self.client_name = QLineEdit(self)
self.client_name.setFixedSize(200, 20)
self.client_name.move(10, 30)
self.label_passwd = QLabel('Введите пароль:', self)
self.label_passwd.move(10, 55)
self.label_passwd.setFixedSize(150, 15)
self.client_passwd = QLineEdit(self)
self.client_passwd.setFixedSize(200, 20)
self.client_passwd.move(10, 75)
self.client_passwd.setEchoMode(QLineEdit.Password)
self.label_conf = QLabel('Введите подтверждение:', self)
self.label_conf.move(10, 100)
self.label_conf.setFixedSize(200, 15)
self.client_conf = QLineEdit(self)
self.client_conf.setFixedSize(200, 20)
self.client_conf.move(10, 120)
self.client_conf.setEchoMode(QLineEdit.Password)
self.btn_ok = QPushButton('Сохранить', self)
self.btn_ok.move(10, 150)
self.btn_ok.setFixedSize(95, 25)
self.btn_ok.clicked.connect(self.save_data)
self.btn_cancel = QPushButton('Выход', self)
self.btn_cancel.move(115, 150)
self.btn_cancel.setFixedSize(95, 25)
self.btn_cancel.clicked.connect(self.close)
self.messages = QMessageBox()
self.show()
def save_data(self):
"""
Метод проверки правильности ввода и сохранения в базу нового пользователя.
"""
if not self.client_name.text():
self.messages.critical(
self, 'Ошибка', 'Не указано имя пользователя.')
return
elif self.client_passwd.text() != self.client_conf.text():
self.messages.critical(
self, 'Ошибка', 'Введённые пароли не совпадают.')
return
elif self.database.check_user(self.client_name.text()):
self.messages.critical(
self, 'Ошибка', 'Пользователь уже существует.')
return
else:
# Генерируем хэш пароля, в качестве соли будем использовать логин в
# нижнем регистре.
passwd_bytes = self.client_passwd.text().encode('utf-8')
salt = self.client_name.text().lower().encode('utf-8')
passwd_hash = hashlib.pbkdf2_hmac(
'sha512', passwd_bytes, salt, 10000)
self.database.add_user(
self.client_name.text(),
binascii.hexlify(passwd_hash))
self.messages.information(
self, 'Успех', 'Пользователь успешно зарегистрирован.')
# Рассылаем клиентам сообщение о необходимости обновить справочники
self.server.service_update_lists()
self.close()
if __name__ == '__main__':
app = QApplication([])
from server_database import ServerDB
database = ServerDB('../server_database.db3')
import os
import sys
path1 = os.path.join(os.getcwd(), '..')
sys.path.insert(0, path1)
from core import Server
server = Server('127.0.0.1', 7777, database)
dial = RegisterUser(database, server)
app.exec_() | yu-messenger-server | /yu_messenger_server-0.0.3-py3-none-any.whl/server/server/add_user.py | add_user.py |
import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication, QLabel, QTableView,\
QDialog, QPushButton, QLineEdit, QFileDialog, QMessageBox
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtCore import Qt, QTimer
import os
# from server.stat_window import StatWindow
# from server.config_window import ConfigWindow
from server.add_user import RegisterUser
from server.remove_user import DelUserDialog
# from add_user import RegisterUser
# from remove_user import DelUserDialog
# GUI - Создание таблицы QModel, для отображения в окне программы.
def gui_create_model(database):
"""
Создаём модель графического интерфейса.
:param database:
:return:
"""
list_users = database.active_users_list()
list_table = QStandardItemModel()
list_table.setHorizontalHeaderLabels(['Имя Клиента', 'IP Адрес', 'Порт', 'Время подключения'])
for row in list_users:
user, ip, port, time = row
user = QStandardItem(user)
user.setEditable(False)
ip = QStandardItem(ip)
ip.setEditable(False)
port = QStandardItem(str(port))
port.setEditable(False)
# Уберём миллисекунды из строки времени, т.к. такая точность не требуется.
time = QStandardItem(str(time.replace(microsecond=0)))
time.setEditable(False)
list_table.appendRow([user, ip, port, time])
return list_table
def create_stat_model(database):
"""
GUI - Функция реализующая заполнение таблицы историей сообщений.
:param database:
:return:
"""
# Список записей из базы
hist_list = database.message_history()
# Объект модели данных:
list_table = QStandardItemModel()
list_table.setHorizontalHeaderLabels(
['Имя Клиента', 'Последний раз входил', 'Сообщений отправлено', 'Сообщений получено'])
for row in hist_list:
user, last_seen, sent, recvd = row
user = QStandardItem(user)
user.setEditable(False)
last_seen = QStandardItem(str(last_seen.replace(microsecond=0)))
last_seen.setEditable(False)
sent = QStandardItem(str(sent))
sent.setEditable(False)
recvd = QStandardItem(str(recvd))
recvd.setEditable(False)
list_table.appendRow([user, last_seen, sent, recvd])
return list_table
class MainWindow(QMainWindow):
"""
Класс основного окна
"""
def __init__(self, database, server, config):
super().__init__()
# База данных сервера
self.database = database
self.server_thread = server
self.config = config
self.initUI()
def initUI(self):
# Кнопка выхода
self.exitAction = QAction('Выход', self)
self.exitAction.setShortcut('Ctrl+Q')
self.exitAction.triggered.connect(qApp.quit)
# Кнопка обновить список клиентов
self.refresh_button = QAction('Обновить список', self)
# Кнопка вывести историю сообщений
self.show_history_button = QAction('История клиентов', self)
# Кнопка настроек сервера
self.config_btn = QAction('Настройки сервера', self)
# Кнопка регистрации пользователя
self.register_btn = QAction('Регистрация пользователя', self)
# Кнопка удаления пользователя
self.remove_btn = QAction('Удаление пользователя', self)
# Статусбар
# dock widget
self.statusBar()
# Тулбар
self.toolbar = self.addToolBar('MainBar')
self.toolbar.addAction(self.exitAction)
self.toolbar.addAction(self.refresh_button)
self.toolbar.addAction(self.show_history_button)
self.toolbar.addAction(self.config_btn)
self.toolbar.addAction(self.register_btn)
self.toolbar.addAction(self.remove_btn)
# Настройки геометрии основного окна
# Поскольку работать с динамическими размерами мы не умеем, и мало времени на изучение, размер окна фиксирован.
self.setFixedSize(1000, 600)
self.setWindowTitle('Messaging Server v 0.0.3')
# Надпись о том, что ниже список подключённых клиентов
self.label = QLabel('Список подключённых клиентов:', self)
self.label.setFixedSize(400, 15)
self.label.move(10, 35)
# Окно со списком подключённых клиентов.
self.active_clients_table = QTableView(self)
self.active_clients_table.move(10, 55)
self.active_clients_table.setFixedSize(780, 400)
# Связываем кнопки с процедурами
self.register_btn.triggered.connect(self.reg_user)
self.remove_btn.triggered.connect(self.rem_user)
# Последним параметром отображаем окно.
self.show()
def reg_user(self):
"""Метод создающий окно регистрации пользователя."""
global reg_window
reg_window = RegisterUser(self.database, self.server_thread)
reg_window.show()
def rem_user(self):
"""Метод создающий окно удаления пользователя."""
global rem_window
rem_window = DelUserDialog(self.database, self.server_thread)
rem_window.show()
class HistoryWindow(QDialog):
"""
Класс окна с историей пользователей
"""
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# Настройки окна:
self.setWindowTitle('Статистика клиентов')
self.setFixedSize(600, 700)
self.setAttribute(Qt.WA_DeleteOnClose)
# Кнопка закрытия окна
self.close_button = QPushButton('Закрыть', self)
self.close_button.move(250, 650)
self.close_button.clicked.connect(self.close)
# Лист с собственно историей
self.history_table = QTableView(self)
self.history_table.move(10, 10)
self.history_table.setFixedSize(580, 620)
self.show()
class ConfigWindow(QDialog):
"""
Класс окна настроек
"""
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
"""
Настройки окна
"""
self.setFixedSize(365, 260)
self.setWindowTitle('Настройки сервера')
# Надпись о файле базы данных:
self.db_path_label = QLabel('Путь до файла базы данных: ', self)
self.db_path_label.move(10, 10)
self.db_path_label.setFixedSize(240, 15)
# Строка с путём базы
self.db_path = QLineEdit(self)
self.db_path.setFixedSize(250, 20)
self.db_path.move(10, 30)
self.db_path.setReadOnly(True)
# Кнопка выбора пути.
self.db_path_select = QPushButton('Обзор...', self)
self.db_path_select.move(275, 28)
def open_file_dialog():
"""
Функция обработчик открытия окна выбора папки.
:return:
"""
global dialog
dialog = QFileDialog(self)
path = dialog.getExistingDirectory()
path = path.replace('/', '\\')
self.db_path.insert(path)
self.db_path_select.clicked.connect(open_file_dialog)
# Метка с именем поля файла базы данных
self.db_file_label = QLabel('Имя файла базы данных: ', self)
self.db_file_label.move(10, 68)
self.db_file_label.setFixedSize(180, 15)
# Поле для ввода имени файла
self.db_file = QLineEdit(self)
self.db_file.move(200, 66)
self.db_file.setFixedSize(150, 20)
# Метка с номером порта
self.port_label = QLabel('Номер порта для соединений:', self)
self.port_label.move(10, 108)
self.port_label.setFixedSize(180, 15)
# Поле для ввода номера порта
self.port = QLineEdit(self)
self.port.move(200, 108)
self.port.setFixedSize(150, 20)
# Метка с адресом для соединений
self.ip_label = QLabel('С какого IP принимаем соединения:', self)
self.ip_label.move(10, 148)
self.ip_label.setFixedSize(180, 15)
# Метка с напоминанием о пустом поле.
self.ip_label_note = QLabel(' оставьте это поле пустым, чтобы\n принимать соединения с любых адресов.', self)
self.ip_label_note.move(10, 168)
self.ip_label_note.setFixedSize(500, 30)
# Поле для ввода ip
self.ip = QLineEdit(self)
self.ip.move(200, 148)
self.ip.setFixedSize(150, 20)
# Кнопка сохранения настроек
self.save_btn = QPushButton('Сохранить', self)
self.save_btn.move(190, 220)
# Кнопка закрытия окна
self.close_button = QPushButton('Закрыть', self)
self.close_button.move(275, 220)
self.close_button.clicked.connect(self.close)
self.show()
# Далее для тестов окна.
# Функция запуска и заполнения главного окна.
def main_win():
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.statusBar().showMessage('Test Statusbar Message')
test_list = QStandardItemModel(main_window)
test_list.setHorizontalHeaderLabels(['Имя Клиента', 'IP Адрес', 'Порт', 'Время подключения'])
test_list.appendRow(
[QStandardItem('test1'), QStandardItem('192.198.0.5'),
QStandardItem('23544'), QStandardItem('16:20:34')])
test_list.appendRow(
[QStandardItem('test2'), QStandardItem('192.198.0.8'),
QStandardItem('33245'), QStandardItem('16:22:11')])
main_window.active_clients_table.setModel(test_list)
main_window.active_clients_table.resizeColumnsToContents()
app.exec_()
# функция запуска и заполнения окна истории
def history_win():
app = QApplication(sys.argv)
window = HistoryWindow()
test_list = QStandardItemModel(window)
test_list.setHorizontalHeaderLabels(
['Имя Клиента', 'Последний раз входил', 'Отправлено', 'Получено'])
test_list.appendRow(
[QStandardItem('test1'), QStandardItem('Fri Dec 12 16:20:34 2020'),
QStandardItem('2'), QStandardItem('3')])
test_list.appendRow(
[QStandardItem('test2'), QStandardItem('Fri Dec 12 16:23:12 2020'),
QStandardItem('8'), QStandardItem('5')])
window.history_table.setModel(test_list)
window.history_table.resizeColumnsToContents()
app.exec_()
# функция запуска и заполнения окна конфигурации
def conf_win():
app = QApplication(sys.argv)
dial = ConfigWindow()
app.exec_()
if __name__ == '__main__':
while True:
print(" 1 - Главное окно \n 2 - Окно истории \n 3 - Окно конфигурации \n 4 - Выход \n")
win_ch = input("выберете номер пункта: ")
if win_ch == "1":
main_win()
if win_ch == "2":
history_win()
if win_ch == "3":
conf_win()
if win_ch == "4":
break | yu-messenger-server | /yu_messenger_server-0.0.3-py3-none-any.whl/server/server/server_gui.py | server_gui.py |
from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKey, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import datetime
class ServerDB:
"""
Класс - серверная база данных
"""
Base = declarative_base()
class AllUsers(Base):
"""
Класс - отображение таблицы всех пользователей
"""
# Создаём таблицу пользователей
__tablename__ = 'all_users'
id = Column(Integer, primary_key=True)
login = Column(String, unique=True)
last_conn = Column(DateTime)
passwd_hash = Column(String)
pubkey = Column(Text)
# Экземпляр этого класса - запись в таблице AllUsers
def __init__(self, login, passwd_hash):
self.login = login
self.last_conn = datetime.datetime.now()
self.passwd_hash = passwd_hash
self.pubkey = None
class ActiveUsers(Base):
"""
Класс - отображение таблицы активных пользователей:
"""
# Создаём таблицу активностей пользователей
__tablename__ = 'active_users'
id = Column(Integer, primary_key=True)
user = Column(String, ForeignKey('all_users.id'), unique=True)
ip = Column(String)
port = Column(Integer)
time_conn = Column(DateTime)
# Экземпляр этого класса - запись в таблице ActiveUsers
def __init__(self, user, ip, port, time_conn):
self.user = user
self.ip = ip
self.port = port
self.time_conn = time_conn
class LoginHistory(Base):
"""
Класс - отображение таблицы истории входов
"""
# Создаём таблицу истории входов в приложение
__tablename__ = 'login_history'
id = Column(Integer, primary_key=True)
user = Column(String, ForeignKey('all_users.id'))
ip = Column(String)
port = Column(Integer)
last_conn = Column(DateTime)
# Экземпляр этого класса - запись в таблице LoginHistory
def __init__(self, user, ip, port, last_conn):
self.user = user
self.ip = ip
self.port = port
self.last_conn = last_conn
class UsersContacts(Base):
"""
Класс - отображение таблицы контактов пользователей
"""
# Создаём таблицу контактов пользователей
__tablename__ = 'contacts'
id = Column(Integer, primary_key=True)
user = Column(String, ForeignKey('all_users.id'))
contact = Column(String, ForeignKey('all_users.id'))
# Экземпляр класса - запись в таблице UsersContacts
def __init__(self, user, contact):
self.user = user
self.contact = contact
class UsersHistory(Base):
"""
Класс отображение таблицы истории действий
"""
# Создаём таблицу истории пользователей
__tablename__ = 'history'
id = Column(Integer, primary_key=True)
user = Column(String, ForeignKey('all_users.id'))
sent = Column(Integer)
accepted = Column(Integer)
# Экземпляр класса - запись в таблице UsersHistory
def __init__(self, user):
self.user = user
self.sent = 0
self.accepted = 0
def __init__(self, path):
"""
Создаём движок базы данных
SERVER_DATABASE - sqlite:///server_base_pre.db3
echo=False - отключает вывод на экран sql-запросов
pool_recycle - по умолчанию соединение с БД через 8 часов простоя обрывается
Чтобы этого не случилось необходимо добавить pool_recycle=7200 (переустановка
соединения через каждые 2 часа)
"""
self.engine = create_engine(
f'sqlite:///{path}',
echo=False,
pool_recycle=7200,
connect_args={
'check_same_thread': False})
# Создаём таблицы
self.Base.metadata.create_all(self.engine)
# Создаём сессию
Session = sessionmaker(bind=self.engine)
self.session = Session()
# Если в таблице активных пользователей есть записи, то их необходимо удалить
# Когда устанавливаем соединение, очищаем таблицу активных пользователей
self.session.query(self.ActiveUsers).delete()
self.session.commit()
def user_login(self, username, ip, port, key):
"""
Функция выполняется при входе пользователя, фиксирует в базе сам факт входа
обновляет открытый ключ пользователя при его изменении.
:param username:
:param ip:
:param port:
:return:
"""
# Запрос в таблицу пользователей на наличие там пользователя с таким именем
rez = self.session.query(self.AllUsers).filter_by(login=username)
# print(type(rez))
# Если имя пользователя уже присутствует в таблице, обновляем время
# последнего входа
if rez.count():
user = rez.first()
user.last_conn = datetime.datetime.now()
if user.pubkey != key:
user.pubkey = key
# Если нет, то создаём нового пользователя
else:
raise ValueError('Пользователь не зарегистрирован.')
# # Создаем экземпляр класса self.AllUsers, через который передаем данные в таблицу
# user = self.AllUsers(username)
# self.session.add(user)
# # Коммит здесь нужен, чтобы в db записался ID
# self.session.commit()
# user_in_history = self.UsersHistory(user.id)
# self.session.add(user_in_history)
# Теперь можно создать запись в таблицу активных пользователей о факте входа.
# Создаем экземпляр класса self.ActiveUsers, через который передаем данные в таблицу
new_active_user = self.ActiveUsers(user.id, ip, port, datetime.datetime.now())
self.session.add(new_active_user)
# и сохранить в историю входов
# Создаем экземпляр класса self.LoginHistory, через который передаем данные в таблицу
history = self.LoginHistory(user.id, ip, port, datetime.datetime.now())
self.session.add(history)
# Сохраняем изменения
self.session.commit()
def user_logout(self, username):
"""
Функция фиксирует отключение пользователя
и удаляет его из активных пользователей.
:param username:
:return:
"""
# Запрашиваем пользователя, что покидает нас
# получаем запись из таблицы AllUsers
user = self.session.query(self.AllUsers).filter_by(login=username).first()
# Удаляем его из таблицы активных пользователей.
# Удаляем запись из таблицы ActiveUsers
self.session.query(self.ActiveUsers).filter_by(user=user.id).delete()
# Применяем изменения
self.session.commit()
def add_user(self, name, passwd_hash):
"""
Метод регистрации пользователя.
Принимает имя и хэш пароля, создаёт запись в таблице статистики.
:param name:
:param passwd_hash:
:return:
"""
user_row = self.AllUsers(name, passwd_hash)
self.session.add(user_row)
self.session.commit()
history_row = self.UsersHistory(user_row.id)
self.session.add(history_row)
self.session.commit()
def remove_user(self, name):
"""
Метод удаляющий пользователя из базы.
:param name:
:return:
"""
user = self.session.query(self.AllUsers).filter_by(login=name).first()
self.session.query(self.ActiveUsers).filter_by(user=user.id).delete()
self.session.query(self.LoginHistory).filter_by(id=user.id).delete()
self.session.query(self.UsersContacts).filter_by(user=user.id).delete()
self.session.query(
self.UsersContacts).filter_by(
contact=user.id).delete()
self.session.query(self.UsersHistory).filter_by(user=user.id).delete()
self.session.query(self.AllUsers).filter_by(login=name).delete()
self.session.commit()
def get_hash(self, name):
"""
Метод получения хэша пароля пользователя.
:param name:
:return:
"""
user = self.session.query(self.AllUsers).filter_by(login=name).first()
return user.passwd_hash
def get_pubkey(self, name):
"""
Метод получения публичного ключа пользователя.
:param name:
:return:
"""
user = self.session.query(self.AllUsers).filter_by(login=name).first()
return user.pubkey
def check_user(self, name):
"""
Метод проверяющий существование пользователя.
:param name:
:return:
"""
if self.session.query(self.AllUsers).filter_by(login=name).count():
return True
else:
return False
def users_list(self):
"""
Функция возвращает список известных пользователей со временем последнего входа.
:return:
"""
# Запрос строк таблицы пользователей.
query = self.session.query(
self.AllUsers.login,
self.AllUsers.last_conn,
)
# Возвращаем список кортежей
return query.all()
def active_users_list(self):
"""
Функция возвращает список активных пользователей
:return:
"""
# Запрашиваем соединение таблиц и собираем кортежи - имя, адрес, порт, время.
query = self.session.query(
self.AllUsers.login,
self.ActiveUsers.ip,
self.ActiveUsers.port,
self.ActiveUsers.time_conn
).join(self.AllUsers)
# Возвращаем список кортежей
return query.all()
def login_history(self, username=None):
"""
Функция возвращает историю входов по пользователю или по всем пользователям
:param username:
:return:
"""
# Запрашиваем историю входа
query = self.session.query(self.AllUsers.login,
self.LoginHistory.last_conn,
self.LoginHistory.ip,
self.LoginHistory.port
).join(self.AllUsers)
# Если было указано имя пользователя, то фильтруем по нему
if username:
query = query.filter(self.AllUsers.login == username)
return query.all()
def process_message(self, sender, recipient):
"""
Функция фиксирует передачу сообщения и делает соответствующие отметки в БД
:param sender:
:param recipient:
:return:
"""
# Получаем ID отправителя и получателя
sender = self.session.query(self.AllUsers).filter_by(login=sender).first().id
recipient = self.session.query(self.AllUsers).filter_by(login=recipient).first().id
# Запрашиваем строки из истории и увеличиваем счётчики
sender_row = self.session.query(self.UsersHistory).filter_by(user=sender).first()
sender_row.sent += 1
recipient_row = self.session.query(self.UsersHistory).filter_by(user=recipient).first()
recipient_row.accepted += 1
self.session.commit()
def add_contact(self, user, contact):
"""
Функция добавляет контакт для пользователя.
:param user:
:param contact:
:return:
"""
# Получаем ID пользователей
user = self.session.query(self.AllUsers).filter_by(login=user).first()
contact = self.session.query(self.AllUsers).filter_by(login=contact).first()
# Проверяем что не дубль и что контакт может существовать (полю пользователь мы доверяем)
if not contact or self.session.query(self.UsersContacts).filter_by(user=user.id, contact=contact.id).count():
return
# Создаём объект и заносим его в базу
contact_row = self.UsersContacts(user.id, contact.id)
self.session.add(contact_row)
self.session.commit()
def remove_contact(self, user, contact):
"""
Функция удаляет контакт из базы данных
:param user:
:param contact:
:return:
"""
# Получаем ID пользователей
user = self.session.query(self.AllUsers).filter_by(login=user).first()
contact = self.session.query(self.AllUsers).filter_by(login=contact).first()
# Проверяем что контакт может существовать (полю пользователь мы доверяем)
if not contact:
return
# Удаляем требуемое
self.session.query(self.UsersContacts).filter(
self.UsersContacts.user == user.id,
self.UsersContacts.contact == contact.id
).delete()
self.session.commit()
def get_contacts(self, username):
"""
Функция возвращает список контактов пользователя.
:param username:
:return:
"""
# Запрашиваем указанного пользователя
user = self.session.query(self.AllUsers).filter_by(login=username).one()
# Запрашиваем его список контактов
query = self.session.query(self.UsersContacts, self.AllUsers.login). \
filter_by(user=user.id). \
join(self.AllUsers, self.UsersContacts.contact == self.AllUsers.id)
# выбираем только имена пользователей и возвращаем их.
return [contact[1] for contact in query.all()]
def message_history(self):
"""
Функция возвращает количество переданных и полученных сообщений.
:return:
"""
query = self.session.query(
self.AllUsers.login,
self.AllUsers.last_conn,
self.UsersHistory.sent,
self.UsersHistory.accepted
).join(self.AllUsers)
# Возвращаем список кортежей
return query.all()
# Отладка
if __name__ == '__main__':
db = ServerDB('../server/server_database.db3')
# Выполняем "подключение" пользователя
db.user_login('client_1', '192.168.1.4', 7778)
db.user_login('client_2', '192.168.1.5', 7777)
# выводим список кортежей - активных пользователей
print(db.active_users_list())
# выполняем 'отключение' пользователя
db.user_logout('client_1')
print(db.users_list())
# выводим список активных пользователей
print(db.active_users_list())
db.user_logout('client_2')
print(db.users_list())
print(db.active_users_list())
# запрашиваем историю входов по пользователю
db.login_history('client_1')
# выводим список известных пользователей
print(db.users_list()) | yu-messenger-server | /yu_messenger_server-0.0.3-py3-none-any.whl/server/server/server_database.py | server_database.py |
import dis
# from pprint import pprint
'''
Метакласс, проверяющий, что в результирующем классе нет клиентских
вызовов таких как: connect. Также проверяется, что серверный
сокет является TCP и работает по IPv4 протоколу.
'''
class ServerVerifier(type):
def __init__(cls, clsname, bases, clsdict):
# clsname - экземпляр метакласса - Server
# bases - кортеж базовых классов - ()
# clsdict - словарь атрибутов и методов экземпляра метакласса
# {'__module__': '__main__',
# '__qualname__': 'Server',
# 'port': <descrptrs.Port object at 0x000000DACC8F5748>,
# '__init__': <function Server.__init__ at 0x000000DACCE3E378>,
# 'init_socket': <function Server.init_socket at 0x000000DACCE3E400>,
# 'main_loop': <function Server.main_loop at 0x000000DACCE3E488>,
# 'process_message': <function Server.process_message at 0x000000DACCE3E510>,
# 'process_client_message': <function Server.process_client_message at 0x000000DACCE3E598>}
# Список методов, которые используются в функциях класса:
methods = [] # получаем с помощью 'LOAD_GLOBAL'
# Обычно методы, обёрнутые декораторами попадают
# не в 'LOAD_GLOBAL', а в 'LOAD_METHOD'
methods_2 = [] # получаем с помощью 'LOAD_METHOD'
# Атрибуты, используемые в функциях классов
attrs = [] # получаем с помощью 'LOAD_ATTR'
# перебираем ключи
for func in clsdict:
# Пробуем
try:
# Возвращает итератор по инструкциям в предоставленной функции
# , методе, строке исходного кода или объекте кода.
ret = dis.get_instructions(clsdict[func])
# ret - <generator object _get_instructions_bytes at 0x00000062EAEAD7C8>
# ret - <generator object _get_instructions_bytes at 0x00000062EAEADF48>
# ...
# Если не функция то ловим исключение
# (если порт)
except TypeError:
pass
else:
# Раз функция разбираем код, получая используемые методы и атрибуты.
for i in ret:
# Печатаем список методов
# print(i)
# i - Instruction(opname='LOAD_GLOBAL', opcode=116, arg=9, argval='send_message',
# argrepr='send_message', offset=308, starts_line=201, is_jump_target=False)
# opname - имя для операции
if i.opname == 'LOAD_GLOBAL':
if i.argval not in methods:
# заполняем список методами, использующимися в функциях класса
methods.append(i.argval)
elif i.opname == 'LOAD_METHOD':
if i.argval not in methods_2:
# заполняем список атрибутами, использующимися в функциях класса
methods_2.append(i.argval)
elif i.opname == 'LOAD_ATTR':
if i.argval not in attrs:
# заполняем список атрибутами, использующимися в функциях класса
attrs.append(i.argval)
# # выводим список используемых методов
# print(20*'-', 'methods', 20*'-')
# pprint(methods)
# print(20*'-', 'methods_2', 20*'-')
# pprint(methods_2)
# print(20*'-', 'attrs', 20*'-')
# pprint(attrs)
# print(50*'-')
# Если обнаружено использование недопустимого метода connect, вызываем исключение:
if 'connect' in methods:
raise TypeError('Использование метода connect недопустимо в серверном классе')
# Если сокет не инициализировался константами SOCK_STREAM(TCP) AF_INET(IPv4), тоже исключение.
if not ('SOCK_STREAM' in attrs and 'AF_INET' in attrs):
raise TypeError('Некорректная инициализация сокета.')
# Обязательно вызываем конструктор предка:
super().__init__(clsname, bases, clsdict)
'''
Метакласс, проверяющий, что в результирующем классе нет серверных
вызовов таких как: accept, listen. Также проверяется, что сокет не
создаётся внутри конструктора класса.
'''
class ClientVerifier(type):
def __init__(cls, clsname, bases, clsdict):
# Список методов, которые используются в функциях класса:
methods = []
for func in clsdict:
# Пробуем
try:
ret = dis.get_instructions(clsdict[func])
# Если не функция, то ловим исключение
except TypeError:
pass
else:
# Раз функция разбираем код, получая используемые методы.
for i in ret:
if i.opname == 'LOAD_GLOBAL':
if i.argval not in methods:
methods.append(i.argval)
# Если обнаружено использование недопустимого метода accept, listen, socket бросаем исключение:
for command in ('accept', 'listen', 'socket'):
if command in methods:
raise TypeError('В классе обнаружено использование запрещённого метода')
# Вызов get_message или send_message из utils считаем корректным использованием сокетов
if 'get_message' in methods or 'send_message' in methods:
pass
else:
raise TypeError('Отсутствуют вызовы функций, работающих с сокетами.')
super().__init__(clsname, bases, clsdict) | yu-messenger-server | /yu_messenger_server-0.0.3-py3-none-any.whl/server/common/metaclasses.py | metaclasses.py |
import exotethys
import os, pickle, shutil
import numpy as np
import pandas as pd
# import pylightcurve as plc
from pylightcurve_master import pylightcurve_self as plc
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from scipy.interpolate import interp1d
from func_pylc import self_fp_over_fs
def update_limbfile(file_path, planet_object, filtername_list, filterchannelnum_list):
"""
Repalce the string list int the 'sail.txt' file
<<input>>
file_path : string ;
planet_object : pylightcurve planet object ; synthetic light curve data ; generated from func:create_planet_tkdata
filtername_list : list(str) ; different filter name ;
filterchannelnum_list : list(int) ; the numbers of filter channel ;
<<output>>
** : running ; execute the update code
"""
file_data="" # the written infromation for each line
with open(file_path, "r", encoding="utf-8") as f:
for line in f:
# the following if-else func. is to replace the parameter which we what to use in exotethys files
if "output_path" in line:
stellar_name = '-'.join(planet_object.name.split("-")[:-1])
line = line.replace(line, f"output_path\t\t\t\t\tData_tk/limb/{stellar_name}\n")
# stellar model will be selected by the diven model and its temperature.
if "stellar_models_grid" in line:
stellar_temperature = planet_object.stellar_temperature
ldc_model = planet_object.ldc_stellar_model
if ldc_model == "atlas":
model_name = "!Phoenix_2018\t!Phoenix_2012_13\t!Phoenix_drift_2012\tAtlas_2000\t!Stagger_2015"
print("Exotethys will use model:Atlas_2000")
elif ldc_model == "phoenix":
if stellar_temperature<10000 and stellar_temperature>3000:
model_name = "!Phoenix_2018\tPhoenix_2012_13\t!Phoenix_drift_2012\t!Atlas_2000\t!Stagger_2015"
print("Exotethys will use model:Phoenix_2012_13")
elif stellar_temperature<3000 and stellar_temperature>1500:
model_name = "!Phoenix_2018\t!Phoenix_2012_13\tPhoenix_drift_2012\t!Atlas_2000\t!Stagger_2015"
print("Exotethys will use model:Phoenix_drift_2012")
else:
print("Please check the stellar temperature range!")
line = line.replace(line, f"stellar_models_grid\t\t\t{model_name}\n")
# passband file need wavelength unit: A(10^-10m)
if "passbands\t" in line:
# add multiple filters
passband_line = "passbands\t\t\t\t\t"
for filtername in filtername_list:
passband_line = passband_line+filtername+".pass\t"
passband_line = passband_line+"\n"
line = line.replace(line,passband_line)
if "wavelength_bins_files" in line:
wavelength_bins_line = "wavelength_bins_files\t\t"
index = 0
for filterchannelnum in filterchannelnum_list:
# not need to bin
if filterchannelnum == 0:
wavelength_bins_line = wavelength_bins_line+"no_bins\t"
index = index+1
continue
# need to pick up the filtername without "filter" inside the string
filter_pickname = '_'.join(filtername_list[index].split("_")[:-1])
wavelength_bins_line = wavelength_bins_line+filter_pickname+'_channel_'+str(filterchannelnum)+'.txt\t'
index = index+1
wavelength_bins_line = wavelength_bins_line+"\n"
line = line.replace(line,wavelength_bins_line)
if "target_names" in line:
line = line.replace(line,"target_names\t\t\t\t"+('-'.join(planet_object.name.split("-")[:-1]))+"\n")
if "star_effective_temperature" in line:
line = line.replace(line,"star_effective_temperature\t\t"+str(planet_object.stellar_temperature)+"\n")
if "star_log_gravity" in line:
line = line.replace(line,"star_log_gravity\t\t\t"+str(planet_object.stellar_logg)+"\n")
if "star_metallicity" in line:
if planet_object.ldc_stellar_model == 'phoenix':
line = line.replace(line,"star_metallicity\t\t\t0.\n")
print("PHOENIX models are only computed for solar metallicity stars. Setting stellar_metallicity = 0.")
else:
line = line.replace(line,"star_metallicity\t\t\t"+str(planet_object.stellar_metallicity)+"\n")
file_data += line
with open(file_path,"w",encoding="utf-8") as f:
f.write(file_data)
return
# calculate the limb darkening coefficient by given .txt file
def run_exotethys(planet_object,
filtername_list, filterchannelnum_list,
re_exotethys=True, re_channel=True, verbose=True):
"""
<<input>>
planet_object : pylightcurve planet object ; the inforamtion of planet parameter ; generated from func:create_planet_tkdata
filtername_list : list(string) ; different filter name ;
filterchannelnum_list : list(int) ; the numbers of filter channel ;
re_exotethys : boolen ; whether to re_exotethys or not
re_channel : boolen ; whether to re_channel or not
verbose : boolen ; print details or not
<<progress>>
** : running ; execute the ldc calculation code
<<output>>
ldc['passbands'] : dict ; the limb darkening coefficents dict ; result calculated by Exotethys package
"""
# check whether the filter need to be channeled or not
filter_channel(filterchannelnum_list, filtername_list, re_channel, verbose)
# because the planet name is HAT-P-xx-b
# HAT-P-xx-c
# HAT-P-xx-...
# the name will split into a list with "-"
# need to merge list element
stellar_name = '-'.join(planet_object.name.split("-")[:-1])
path_save = 'Data_tk/limb/'+stellar_name
# check if it already have file
if not os.path.isfile(path_save+'/'+stellar_name+'_ldc.pickle'):
print("Don't find the limb darkening coefficient file!!!")
print("Start to call \"exotethys\" to calculate ")
# check if there is the save folder
if not os.path.isdir(path_save):
os.makedirs(path_save)
# update the file.txt exotethys need
shutil.copy("Data_tk/limb/sail_example.txt" , f"Data_tk/limb/{stellar_name}/sail.txt")
update_limbfile(f"Data_tk/limb/{stellar_name}/sail.txt", planet_object, filtername_list, filterchannelnum_list)
# do the limb darkening coefficient calculation
# (it will "interpolate the stellar profile" with different parameter)
exotethys.sail.ldc_calculate(f"Data_tk/limb/{stellar_name}/sail.txt")
# re_exotethys
elif re_exotethys == True:
print("Need to recalculate the limb darkening coefficient file!!!")
print("Start to call \"exotethys\" to calculate ")
# update the file.txt exotethys need
shutil.copy("Data_tk/limb/sail_example.txt" , f"Data_tk/limb/{stellar_name}/sail.txt")
update_limbfile(f"Data_tk/limb/{stellar_name}/sail.txt",planet_object, filtername_list, filterchannelnum_list)
# check if there is the save folder
if not os.path.isdir(path_save):
os.makedirs(path_save)
# do the limb darkening coefficient calculation
exotethys.sail.ldc_calculate(f"Data_tk/limb/{stellar_name}/sail.txt") # it will "interpolate the stellar profile" with different parameter
# load the result data and get coefficient
print("Get the limb darkening coefficient file!!!")
ldc = pickle.load(open(f"Data_tk/limb/{stellar_name}/{stellar_name}_ldc.pickle",'rb'),encoding='latin1')
return ldc['passbands']
def filter_channel(filterchannelnum_list, filtername_list, re_channel, verbose):
"""
<<input>>
filterchannelnum_list : list(int) ; the numbers of filter channel
filtername_list : list(str) ; different filter name
re_channel : boolen ; whether to re_channel or not
verbose : boolen ; print details or not
<<output>>
** : running ; execute the update code
"""
if not len(filterchannelnum_list)==len(filtername_list):
print("filterchannelnum_list should have same len as filtername_list")
return
index = 0
for filterchannelnum in filterchannelnum_list:
filtername = filtername_list[index]
filter_pickname = '_'.join(filtername.split("_")[:-1]) # need to pick up the filtername without "filter" inside the string
# if nobins, we do not need to generate the additional channel filter files
if filterchannelnum == 0:
print(f"The filter {filter_pickname} don't need to do filter channeling")
index = index+1
continue
# if there was the default channel data, just pick the information and print them
elif filterchannelnum == 'default' and not re_channel:
print(f"The filter {filter_pickname} use the default filter channeling")
df_filter = pd.read_csv(f"Data_tk/passband/channel/{filter_pickname}_channel_default.txt",
sep='\t', header=None, names=['low', 'high']) # load the filter data
print(f"Divide {filter_pickname} into {len(df_filter)} wavelength channels")
if verbose:
print(df_filter)
fig = plt.figure(figsize=(8,6), dpi=100)
channelplot = mpimg.imread(f'Data_tk/passband/channel/{filter_pickname}_channel_default'+'.png')
plt.imshow(channelplot, aspect='auto')
plt.axis('off')
plt.show()
index = index+1
continue
# if there was the channel data generated before, just pick the information and print them
elif os.path.isfile(f"Data_tk/passband/channel/{filter_pickname}_channel_{filterchannelnum}.txt") and not re_channel:
print(f"The {filter_pickname} filter channel file with {filterchannelnum} channel was generated before!")
df_filter = pd.read_csv(f"Data_tk/passband/channel/{filter_pickname}_channel_{filterchannelnum}.txt",
sep='\t', header=None, names=['low', 'high']) # load the filter data
print(f"Divide {filter_pickname} into {filterchannelnum} wavelength channels")
print(f"Each channel has a {(df_filter.loc[0]['high']-df_filter.loc[0]['low'])}(A) wavelength interval.")
if verbose:
print(df_filter)
fig = plt.figure(figsize=(8,6), dpi=100)
channelplot = mpimg.imread(f"Data_tk/passband/channel/{filter_pickname}_channel_{filterchannelnum}.png")
plt.imshow(channelplot, aspect='auto')
plt.axis('off')
plt.show()
index = index+1
continue
index = index+1
print(f"run/re_channel the filter channeling process of {filtername} in {filterchannelnum} number of channeling")
if filterchannelnum == 'default':
print(f"The filter {filter_pickname} use the default filter channeling")
df_filter = pd.read_csv(f"Data_tk/passband/{filtername}.pass", sep='\t',
header=None, names=['Wavelength(A)', 'tranmission rate']) # load the filter data
wavelength = df_filter['Wavelength(A)'].to_numpy()
df = pd.read_csv(f"Data_tk/passband/channel/{filter_pickname}_channel_default.txt",
sep='\t', header=None, names=['low', 'high']) # load the filter data
print(f"Divide {filter_pickname} into {len(df)} wavelength channels")
print(df)
# plot the channeling filter
[df['low'].to_list()[0]-1]+df['high'].to_list()
channel_point_df = np.array([df['low'].to_list()[0]-1]+df['high'].to_list())
# beacuse the first interval will be left limit < interval <= right limit,
# the first left limit will be missed, so we apprend one more point
filterchannelnum_savefig = filterchannelnum
filterchannelnum = len(df)
else:
df_filter = pd.read_csv(f"Data_tk/passband/{filtername}.pass", sep='\t',
header=None, names=['Wavelength(A)', 'tranmission rate']) # load the filter data
wavelength = df_filter['Wavelength(A)'].to_numpy()
channel_point = np.linspace(wavelength.min(),wavelength.max(), filterchannelnum+1)
df = pd.DataFrame()
df['low'] = channel_point[:-1]
df['high'] = channel_point[1:]
df.to_csv(f"Data_tk/passband/channel/{filter_pickname}_channel_{filterchannelnum}.txt", sep='\t', index=False, header=False)
print(f"Divide {filter_pickname} into {filterchannelnum} wavelength channels")
print(f"Each channel has a {(channel_point[1]-channel_point[0])}(A) wavelength interval.")
print(df)
# plot the channeling filter
channel_point_df = np.append(channel_point[0]-1, channel_point[1:])
# beacuse the first interval will be left limit < interval <= right limit,
# the first left limit will be missed, so we apprend one more point
filterchannelnum_savefig = filterchannelnum
# add the label of belonging channel for each row
df_filter['channel'] = pd.cut(df_filter['Wavelength(A)'], channel_point_df, labels=list(range(filterchannelnum)))
# plot
plot_filterchannel(filterchannelnum, filter_pickname, df_filter, df, filterchannelnum_savefig)
return
def plot_filterchannel(filterchannelnum, filter_pickname, df_filter, df, filterchannelnum_savefig):
"""
<<input>>
filterchannelnum : int ; the numbers of filter channel
filter_pickname : string ; (original) filter name
df_filter : dataframe ; the table of (original) filter transmission information in its range
df : dataframe ; the table of (original) filter channel information with left/right edge
filterchannelnum_savefig : int/string ; the string when saving the channel filter profile figure
<<output>>
figure : figure ; under path: 'Data_tk/passband/channel/
"""
colors = plt.cm.jet(np.linspace(0,1,filterchannelnum)) # the color map with gradually change (.jet is one kind of cmap)
fig = plt.figure(figsize=(8,6), dpi=100, constrained_layout=True)
fig.suptitle(f"The channeling {filter_pickname} filter with {filterchannelnum} channels")
fig.patch.set_facecolor('white')
ax = fig.add_subplot(111)
for i in range(filterchannelnum):
ymean = df_filter['tranmission rate'][df_filter.channel==i].mean()
each_w = df_filter['Wavelength(A)'][df_filter.channel==i].to_list()
each_t = df_filter['tranmission rate'][df_filter.channel==i].to_list()
# consider the separated channel details (the upper and lower boundary probem when face separated line),
# using interpolation to find the appropriate value when wavelength go to separate into two channels
if i == 0: # when the left limit of boundary
f_right = interp1d([each_w[-1], df_filter['Wavelength(A)'][df_filter.channel==i+1].to_list()[0]],
[each_t[-1], df_filter['tranmission rate'][df_filter.channel==i+1].to_list()[0]])
each_w = [df.loc[i]['low']] + each_w + [df.loc[i]['high'] , df.loc[i]['high']]
each_t = [0] + each_t + [f_right(df.loc[i]['high']), 0]
elif i == filterchannelnum-1: # when the right limit of boundary
f_left = interp1d([df_filter['Wavelength(A)'][df_filter.channel==i-1].to_list()[-1], each_w[0]],
[df_filter['tranmission rate'][df_filter.channel==i-1].to_list()[-1], each_t[0]])
each_w = [df.loc[i]['low'], df.loc[i]['low']] + each_w + [df.loc[i]['high']]
each_t = [0, f_left(df.loc[i]['low'])] + each_t + [0]
else: # boundary of each channel
f_left = interp1d([df_filter['Wavelength(A)'][df_filter.channel==i-1].to_list()[-1], each_w[0]],
[df_filter['tranmission rate'][df_filter.channel==i-1].to_list()[-1], each_t[0]])
f_right = interp1d([each_w[-1], df_filter['Wavelength(A)'][df_filter.channel==i+1].to_list()[0]],
[each_t[-1], df_filter['tranmission rate'][df_filter.channel==i+1].to_list()[0]])
each_w = [df.loc[i]['low'], df.loc[i]['low']] + each_w + [df.loc[i]['high'], df.loc[i]['high']]
each_t = [0, f_left(df.loc[i]['low'])] + each_t + [f_right(df.loc[i]['high']),0]
each_w = np.array(each_w)
each_t = np.array(each_t)
ax.plot(each_w/1e4, each_t, color=colors[i])
ax.annotate(f"c{i}", xy=(each_w.mean()/1e4, ymean))
ax.set_xlabel('Wavelength(um)')
ax.set_ylabel('tranmission rate')
ax.set_ylim(0,1)
plt.savefig(f"Data_tk/passband/channel/{filter_pickname}_channel_{filterchannelnum_savefig}.png")
plt.show()
return
def gen_filtername_allchannellist(ldc_filter, filtername_list, filterchannelnum_list, planet_tk):
"""
<<input>>
ldc_filter : dict ; the limb darkening coefficents dict
filtername_list : list(str) ; different filter (original) name
filterchannelnum_list : list(int) ; the numbers of filter channel
planet_tk : pylightcurve planet object ; the inforamtion of planet parameter ; generated from func:create_planet_tkdata
<<output>>
filtername_allchannellist : list(str) ; different filter (+channel) name
"""
filter_index = 0
filtername_allchannellist = []
for filter_name in list(ldc_filter.keys()):
filter_pickname = filter_name.split(".pass")[0]
filter_pickwave = '_'.join(filter_name.split(".pass")[1].split("_")[1:])
if filtername_list[filter_index] != filter_pickname:
filter_index= filter_index+1
if (filterchannelnum_list[filter_index] == 0) and (filter_pickwave != ''):
continue
# here, the self_fp_over_fs need the filter name to load the "transmission rate"
filter_fp= self_fp_over_fs(planet_tk.rp_over_rs,
planet_tk.sma_over_rs,
planet_tk.albedo,
planet_tk.emissivity,
planet_tk.stellar_temperature,
filter_pickname,
filter_pickwave)
ldc1, ldc2, ldc3, ldc4 = ldc_filter[filter_name]['claret4']['coefficients']
if filter_pickwave == '':
print(filter_pickname, ldc_filter[filter_name]['claret4']['coefficients'])
planet_tk.add_filter(filter_pickname+filter_pickwave, planet_tk.rp_over_rs,
ldc1, ldc2, ldc3, ldc4, filter_fp)
filtername_allchannellist.append(filter_pickname)
else:
print(filter_pickname+'-'+filter_pickwave, ldc_filter[filter_name]['claret4']['coefficients'])
planet_tk.add_filter(filter_pickname+'-'+filter_pickwave, planet_tk.rp_over_rs,
ldc1, ldc2, ldc3, ldc4, filter_fp)
filtername_allchannellist.append(filter_pickname+'-'+filter_pickwave)
return filtername_allchannellist | yu-twinkle | /yu_twinkle-0.0.2.tar.gz/yu_twinkle-0.0.2/yu_twinkle/func_exotethys.py | func_exotethys.py |
import pickle, os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from astropy.time import Time
def get_fitting_result(target_name, target_date, binsize_list, filtername_list, exposure_list):
"""
<<input>>
target_name : string ; the target name
target_date : string ; the date of available observation ; determined by LC_syn_tk.py
binsize_list : list(int) ; the binsize list for all binsize
filtername_list : list(str) ; different filter name
exposure_list : list(int) ; different exposure time list
<<output>>
fitting result : dictionary ; getting the fitting result form each fitting result's folder
"""
stellar_name= '-'.join(target_name.split('-')[:-1])
data_bin = pickle.load(open(f"Savefile/{stellar_name}/{target_name}/{target_date}/time_flux/{target_name}_bin_{target_date}.pickle",'rb'))
data_fitting = {}
# data_fitting["rp"] = {}
# data_fitting["rp_low"] = {}
# data_fitting["rp_high"] = {}
data_fitting["tmid"] = {}
data_fitting["tmid_low"] = {}
data_fitting["tmid_high"] = {}
data_fitting["rechi"] = {}
# for mode in ['mod', 'obs']:
for mode in ["obs"]:
# data_fitting["rp"][mode] = {}
# data_fitting["rp_low"][mode] = {}
# data_fitting["rp_high"][mode] = {}
data_fitting["tmid"][mode] = {}
data_fitting["tmid_low"][mode] = {}
data_fitting["tmid_high"][mode] = {}
data_fitting["rechi"][mode] = {}
for bin_t in binsize_list:
# for finding the path of the fitting result
if bin_t == 0:
bin_name = "non-binned"
else:
bin_name = f"bin{bin_t}"
# data_fitting["rp'][mode][bin_t] = {}
# data_fitting["rp_low'][mode][bin_t] = {}
# data_fitting["rp_high"][mode][bin_t] = {}
data_fitting["tmid"][mode][bin_t] = {}
data_fitting["tmid_low"][mode][bin_t] = {}
data_fitting["tmid_high"][mode][bin_t] = {}
data_fitting["rechi"][mode][bin_t] = {}
index = 0
for filtername in filtername_list:
# the list to save the information of each exposure time
# in the same filter/ bin_t
# rp_t = []
# rp_low_t = []
# rp_high_t = []
tmid_t = []
tmid_low_t = []
tmid_high_t = []
rechi_t = []
# data_fitting["rp"][mode][bin_t][filtername] = {}
# data_fitting["rp_low"][mode][bin_t][filtername] = {}
# data_fitting["rp_high"][mode][bin_t][filtername] = {}
data_fitting["tmid"][mode][bin_t][filtername] = {}
data_fitting["tmid_low"][mode][bin_t][filtername] = {}
data_fitting["tmid_high"][mode][bin_t][filtername] = {}
data_fitting["rechi"][mode][bin_t][filtername] = {}
# search the rp/rs&t_mid we want from each exposure time's fitting result
for exp_t in exposure_list[index]:
if not bin_name == "non-binned":
if data_bin[f"check_expvsbin_t{bin_t} [min]"][filtername][f"exp_t{exp_t} [sec]"]:
continue
path = f"Savefile/{stellar_name}/{target_name}/{target_date}/fitting/{bin_name}/{bin_name}_t{exp_t}_{mode}_{filtername}_fit/results.txt"
df = pd.read_csv(path , sep='\s+') # the .txt result file
# row_rp = df.loc[df['#'] == 'rp_'+filtername]
row_tmid = df.loc[df['#'] == "T_mid_0"]
row_rechi = df.loc[df['#'] == "#Reduced"]
# data_fitting['rp'][mode][bin_t][filtername][exp_t] = float(row_rp['variable'].values)
# data_fitting['rp_low'][mode][bin_t][filtername][exp_t] = float(row_rp['result'].values)
# data_fitting['rp_high'][mode][bin_t][filtername][exp_t] = float(row_rp['uncertainty'].values)
data_fitting["tmid"][mode][bin_t][filtername][exp_t] = float(row_tmid["variable"].values)
data_fitting["tmid_low"][mode][bin_t][filtername][exp_t] = float(row_tmid["result"].values)
data_fitting["tmid_high"][mode][bin_t][filtername][exp_t] = float(row_tmid["uncertainty"].values)
data_fitting["rechi"][mode][bin_t][filtername][exp_t] = float(row_rechi["uncertainty"].values)
index = index + 1
return data_fitting
def gen_fitresult_csv(data_dict, binsize_list, filtername_list, exposure_list, target_name, target_date, real_mid_time):
"""
<<input>>
data_dict : dtaframe ; the csv file of fthe fitting result ; generated func:gen_fitresult_csv=
binsize_list : list(int) ; the binsize list for all binsize
filtername_list : list(str) ; different filter name
exposure_list : list(int) ; different exposure time list
target_name : string ; the target name
target_date : string ; the date of available observation ; determined by LC_syn_tk.py
real_mid_time : float ; the real mid_time time we given in the Twinkle data
<<output>>
csv file : csv dataframe ; under path: Result/{target_name}/fitting/{target_date}/fitting_result_bin_{target_name}_{target_date}.csv
"""
data_csv = {}
data_csv = pd.DataFrame(data_csv)
for mode in ["obs"]:
# for mode in ['mod', 'obs']:
# for bin_element in [0]:
for bin_t in binsize_list:
for filtername in filtername_list:
filter_index = filtername_list.index(filtername)
data_csv_ = {
"time_mode" : "",
"binsize [min]" : "",
"exp_t [sec]" : "",
"filtername" : "",
"$\Delta$tmid [min]" : data_dict["tmid"][mode][bin_t][filtername],
"tmid_errorbar [min]": "",
"tmid_low [min]" : data_dict["tmid_low"][mode][bin_t][filtername],
"tmid_high [min]" : data_dict["tmid_high"][mode][bin_t][filtername],
"tmid [BJD]" : data_dict["tmid"][mode][bin_t][filtername],
# "$\Delta$rp [%]" : data_dict['rp'][mode][bin_t][filtername],
# "rp_errorbar [%]" : "",
# "rp_low [%]" : data_dict['rp_low'][mode][bin_t][filtername],
# "rp_high [%]" : data_dict['rp_high'][mode][bin_t][filtername],
# "rp [rp/rs]" : data_dict['rp'][mode][bin_t][filtername],
"rechi" : data_dict["rechi"][mode][bin_t][filtername]
}
data_csv_ = pd.DataFrame(data_csv_)
data_csv_["binsize [min]"] = [bin_t]*len(data_csv_.index)
data_csv_["exp_t [sec]"] = data_csv_.index
data_csv_["time_mode"] = [mode]*len(data_csv_.index)
data_csv_["filtername"] = [filtername]*len(data_csv_.index)
data_csv_["$\Delta$tmid [min]"] = round((data_csv_["$\Delta$tmid [min]"]-real_mid_time)*24*60, 3)
data_csv_["tmid_errorbar [min]"] = round((data_csv_["tmid_high [min]"]+(-data_csv_["tmid_low [min]"]))*24*60, 2)
data_csv_["tmid_low [min]"] = round(data_csv_["tmid_low [min]"]*24*60, 2)
data_csv_["tmid_high [min]"] = round(data_csv_["tmid_high [min]"]*24*60, 2)
data_csv_["tmid [BJD]"] = round(data_csv_["tmid [BJD]"], 5)
# data_csv_["$\Delta$rp [%]"] = round(((data_csv_["$\Delta$rp [%]"]-real_rp)/real_rp)*100, 3)
# data_csv_["rp_errorbar [%]"] = round(((data_csv_["rp_high [%]"]+(-data_csv_["rp_low [%]"]))/real_rp)*100, 2)
# data_csv_["rp_low [%]"] = round((data_csv_["rp_low [%]"]/real_rp)*100, 2)
# data_csv_["rp_high [%]"] = round((data_csv_["rp_high [%]"]/real_rp)*100, 2)
# data_csv_["rp [rp/rs]"] = round(data_csv_["rp [rp/rs]"], 3)
data_csv_["rechi"] = round(data_csv_["rechi"], 3)
data_csv = pd.concat([data_csv, data_csv_])
# check if there is the save folder
if not os.path.isdir(f"Result/{target_name}/fitting/{target_date}"):
print(f"create the folder under path:Result/{target_name}/fitting/{target_date}")
os.makedirs(f"Result/{target_name}/fitting/{target_date}")
data_csv.to_csv(f"Result/{target_name}/fitting/{target_date}/fitting_result_bin_{target_name}_{target_date}.csv", index=False)
return data_csv
def plot_midt_fitting_result(df, target_name, target_date, binsize_list,
mode, filtername, real_mid_time,
filename,
save=True):
"""
<<input>>
df : dtaframe ; the csv file of fthe fitting result ; generated func:gen_fitresult_csv
target_name : string ; the target name
target_date : string ; the date of available observation ; determined by LC_syn_tk.py
binsize_list : list(int) ; the binsize list for all binsize
mode : string ; which type of mode will be plotted ; consider "whole tranist time"/"observable time"
filtername : string ; the filtername that you want to generate its fitting result figure
real_mid_time : float ; the real mid_time time we given in the Twinkle data
filename : string ; the figure saving path and name
save : boolen ; whether save the figure or not ; default= True
<<output>>
figure : figure ; under path: Result/{target_name}/fitting/{target_date}/
"""
fs=20
expt_list = [60, 120, 240, 480]
marker_list = ['o', 'X', '^', 's']
ls_list = ['-', '--', '-.', ':']
colors_list = ['C0', 'C1', 'C2', 'C3']
fig1 = plt.figure(figsize=(10,6), dpi=200, tight_layout=True)
fig1.suptitle(target_name+" with "+filtername+": compare different parameters\n"+\
"Mid_Time="+Time(real_mid_time, format='jd').iso ,fontsize=fs)
fig1.patch.set_facecolor('white')
# plot !!!
ax = fig1.add_subplot(1, 1, 1)
ax.set_title(f"\"Mid_Time\" ({mode})",fontsize=fs*0.8)
ax.plot([1,2,3,4,5,6,7],
np.full(7, 0.0),
color='k')
yt_max = 0
yt_min = 0
# ==========================================================================================================
for exp_t in expt_list:
for filtername in ["Twinkle_ch0_filter"]:
df_exp = df[df["exp_t [sec]"]==exp_t]
df_filter_bool = df_exp["filtername"]==filtername
tmid_obs = df_exp[df_filter_bool]["$\Delta$tmid [min]"].values
tmid_low_obs = df_exp[df_filter_bool]["tmid_low [min]"].values
tmid_high_obs = df_exp[df_filter_bool]["tmid_high [min]"].values
yt_max = max(yt_max, max(tmid_obs + tmid_high_obs))
yt_min = min(yt_min, min(tmid_obs + tmid_low_obs))
# 檢查這一個binsize缺少了哪一些 要挑哪一些
x_list = []
bin_list_df = df_exp[df_filter_bool]["binsize [min]"].values
for bin_t_thisbinlist in bin_list_df:
x_index = binsize_list.index(bin_t_thisbinlist)
x_list.append(x_index)
x_list = np.array(x_list)
# ==========================================================================================================
ax.errorbar(x_list+1, tmid_obs,
yerr = [-tmid_low_obs, tmid_high_obs],
fmt = '', markersize=8, capsize=8, lw=2,
color=colors_list[expt_list.index(exp_t)],
marker = marker_list[expt_list.index(exp_t)],
ls = ls_list[expt_list.index(exp_t)],
zorder = 7-expt_list.index(exp_t), alpha=1,
label = f"exp_t={exp_t}[sec]")
ax.set_xlabel("Data binning [min]",fontsize=fs*0.6)
ax.set_ylabel("$\Delta$Mid_T [min]",fontsize=fs*0.6)
ax.tick_params(axis='y', labelsize= fs*0.5)
xticks = ["non-binned", "bin5", "bin10", "bin15", "bin20", "bin25", "bin30"]
# xticks = df[df['exp_t [sec]']==60][df[df['exp_t [sec]']==60]['filtername']==filtername]['binsize [min]'].values
ax.set_xticks(np.arange(7)+1, labels=xticks, fontsize=fs*0.6)
ax.axis(ymin=yt_min*1.5,ymax=yt_max*1.2)
ax.legend(loc = 'lower right', prop={'size': fs*0.5}, ncol=4)
# check if there is the save folder
if not os.path.isdir(f"Result/{target_name}/fitting/{target_date}"):
print(f"create the folder under path:Result/{target_name}/fitting/{target_date}")
os.makedirs(f"Result/{target_name}/fitting/{target_date}")
if save:
plt.savefig(f"{filename}.png")
plt.show()
return | yu-twinkle | /yu_twinkle-0.0.2.tar.gz/yu_twinkle-0.0.2/yu_twinkle/func_view_fitting.py | func_view_fitting.py |
import pandas as pd
import json
from astropy.time import Time
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interp1d
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
def plot_avail(data):
fs=18
plt.figure(figsize=(10,6))
for ii in range(np.shape(data)[0]):
times = data_avail[ii]
t = Time(times, format='isot', scale='utc')
year = int(data[ii][0][0:4])
year_start = Time([f'{year}-01-01T00:00:00.000'], format='isot', scale='utc')
day_start = t[0].jd - year_start.jd
day_end = t[1].jd - year_start.jd
plt.plot([day_start,day_end],[year,year],lw=4,c='r')
plt.scatter([day_start,day_end],[year,year],c='r',marker='d',s=80)
plt.xlim(0,365)
plt.ylim(2023,2030)
plt.xlabel('Day',fontsize=fs)
plt.ylabel('Year',fontsize=fs)
plt.xticks(fontsize=fs-2)
plt.yticks(fontsize=fs-2)
plt.show()
def plot_cartopy(data, num_levels):
X = data['full_ra']
Y = data['full_dec']
plot_data = data['full_coverage']
#sun = pd.read_csv('sun_coord.csv')
#interp_ecliptic = interp1d(sun['RA'],sun['Dec'],bounds_error=None, fill_value='extrapolate')
#ecliptic_dec = interp_ecliptic(X)
fs = 14
levels = MaxNLocator(nbins=num_levels).tick_values(np.min(plot_data)-1, np.max(plot_data)+1)
cmap = plt.get_cmap('Spectral_r')
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
#plt.style.use("dark_background")
fig = plt.figure(figsize=(10,6))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.Mollweide(central_longitude=180))
cs = ax.contourf(X,Y,plot_data, levels = levels,
transform=ccrs.PlateCarree(),
cmap=cmap, norm = norm)
cbar = plt.colorbar(cs, ax = ax, shrink = 0.6)
cbar.ax.set_ylabel('Total Time Available [Days/Year]', fontsize = fs-2)
ax.scatter(data['ra'],data['dec'],c='w',edgecolor='k',transform=ccrs.PlateCarree(),lw=0.5)
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
linewidth=0.5, color='black', linestyle=':')
gl.bottom_labels = False
gl.top_labels = False
gl.left_labels = False
gl.right_labels = False
gl.xlines = True
gl.ylines = True
text_ra = [60,120,180,240,300]
for ii in text_ra:
if ii < 100:
ax.text(ii-5,-2.5,f'{ii}$^\circ$',transform=ccrs.PlateCarree(),fontsize=fs)
else:
ax.text(ii-10,-2.5,f'{ii}$^\circ$',transform=ccrs.PlateCarree(),fontsize=fs)
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
ax.text(-0.07, 0.55, 'Declination', va='bottom', ha='center',
rotation='vertical', rotation_mode='anchor',
transform=ax.transAxes, fontsize = fs)
ax.text(0.5, -0.2, 'Right Ascension', va='bottom', ha='center',
rotation='horizontal', rotation_mode='anchor',
transform=ax.transAxes, fontsize = fs)
ax.text(-0.02, 0.475, '0$^\circ$', va='bottom', ha='center',
rotation='horizontal', rotation_mode='anchor',
transform=ax.transAxes, fontsize = fs)
ax.text(0.015, 0.68, '30$^\circ$', va='bottom', ha='center',
rotation='horizontal', rotation_mode='anchor',
transform=ax.transAxes, fontsize = fs)
ax.text(0.14, 0.87, '60$^\circ$', va='bottom', ha='center',
rotation='horizontal', rotation_mode='anchor',
transform=ax.transAxes, fontsize = fs)
ax.text(0.015, 0.24, '-30$^\circ$', va='bottom', ha='center',
rotation='horizontal', rotation_mode='anchor',
transform=ax.transAxes, fontsize = fs)
ax.text(0.14, 0.06, '-60$^\circ$', va='bottom', ha='center',
rotation='horizontal', rotation_mode='anchor',
transform=ax.transAxes, fontsize = fs)
plt.show()
def plot_transit(data,lc_num):
t_start = Time(data['transit'][lc_num]['start_time'])
t_end = Time(data['transit'][lc_num]['end_time'])
t_mid = Time((t_start.jd + t_end.jd)/2., format='jd')
mid_date = Time(t_mid.iso , out_subfmt='date').iso
time = np.linspace(t_start.jd,t_end.jd,len(data['lc']))
fs = 18
plt.figure(figsize=(8,4))
plt.plot(time,data['lc'],c='k',lw=2)
for ii in range(len(data['transit'][lc_num]['viewing_times'])):
view_start = Time(data['transit'][lc_num]['viewing_times'][ii][0])
view_end = Time(data['transit'][lc_num]['viewing_times'][ii][1])
plt.fill_between([view_start.jd,view_end.jd],[0.1,0.1],[1.5,1.5],color='g',alpha=0.2, label=f'Visable Channel{ii+1}')
td = 1-min(data['lc'])
plt.xlim(min(time),max(time))
plt.ylim(1-1.4*td,1. + td*0.2)
plt.xlabel('Time [BJD]',fontsize=fs)
plt.ylabel('Relative Flux',fontsize=fs)
plt.xticks(fontsize=fs-2)
plt.yticks(fontsize=fs-2)
plt.legend()
plt.title(f"Date: {mid_date} | Coverage: {np.round(data['transit'][lc_num]['coverage']*100,1)}%",fontsize=fs-2)
plt.show()
def replot_star_data(data, col):
fs=18
plt.figure(figsize=(10,6))
plt.scatter(data['ch0']['wavelength'],data['ch0'][col],c='w',edgecolor='b')
plt.scatter(data['ch1']['wavelength'],data['ch1'][col],c='w',edgecolor='r')
plt.xlim(0.5,4.5)
plt.xlabel('Wavelength [$\mu$m]',fontsize=fs)
if col == 'error_per_hour':
plt.ylabel('Error Per Hour [ppm]',fontsize=fs)
elif col == 'error_per_exposure':
plt.ylabel('Error Per Exposure [ppm]',fontsize=fs)
plt.title(f"Exposure Time: {np.round(data['exposure_time'],2)} s",fontsize=fs-4)
plt.xticks(fontsize=fs-2)
plt.yticks(fontsize=fs-2)
plt.show()
def replot_transit_data(data, num_sh):
fs=18
plt.figure(figsize=(10,6))
plt.scatter(data['ch0']['wavelength'],data['ch0'][f'transit_snr_{num_sh}sh'],c='w',edgecolor='b')
plt.scatter(data['ch1']['wavelength'],data['ch1'][f'transit_snr_{num_sh}sh'],c='w',edgecolor='r')
plt.xlim(0.5,4.5)
plt.xlabel('Wavelength [$\mu$m]',fontsize=fs)
plt.ylabel(f'Transit SNR ({num_sh} Scale Heights)',fontsize=fs)
plt.xticks(fontsize=fs-2)
plt.yticks(fontsize=fs-2)
plt.show()
fs=18
plt.figure(figsize=(10,6))
plt.scatter(data['ch0']['wavelength'],data['ch0']['eclipse_snr'],c='w',edgecolor='b')
plt.scatter(data['ch1']['wavelength'],data['ch1']['eclipse_snr'],c='w',edgecolor='r')
plt.xlim(0.5,4.5)
plt.xlabel('Wavelength [$\mu$m]',fontsize=fs)
plt.ylabel('Eclipse SNR',fontsize=fs)
plt.xticks(fontsize=fs-2)
plt.yticks(fontsize=fs-2)
plt.show() | yu-twinkle | /yu_twinkle-0.0.2.tar.gz/yu_twinkle-0.0.2/yu_twinkle/func_stardrive.py | func_stardrive.py |
# In[ ]:
import os, copy, pickle
import numpy as np
import pandas as pd
# import pylightcurve as plc
from pylightcurve_master import pylightcurve_self as plc
# The package for parallel computing
import multiprocessing
# In[ ]:
def add_observation(planet,
exp_t,
time_array,
flux_array,
flux_unc_array,
filtername):
planet.add_observation(time = time_array,
time_format = 'BJD_TDB',
exp_time = exp_t,
time_stamp = 'mid',
flux = flux_array,
flux_unc = flux_unc_array,
flux_format = 'flux',
filter_name = filtername)
# In[ ]:
def run_fitting(planet, date, exp_t, bin_size, filtername, mode):
"""
<<input>>
planet : pylightcurve planet object ; synthetic light curve data ; generated from func:create_planet_tkdata
date : string ; observation date ; the chosen date of available observation by Starfrive tool
exp_t : int ; exposure time ; will be determined in LC_fitting.py
binsize : int ; bin size
filtername : string ; filter name
mode : string ; consider "whole time"/"observable time" ; 'mod' / 'obs']
<<output>>
** : running ; execute the fitting code ; generated the mcmc_fitting
"""
save_planet = planet.name
save_stellar = '-'.join(save_planet.split('-')[:-1])
# check if there is the save folder
if not os.path.isdir(f"Savefile/{save_stellar}/{save_planet}/{date}/fitting/{bin_size}"):
os.makedirs(f"Savefile/{save_stellar}/{save_planet}/{date}/fitting/{bin_size}")
# path of saving file
save_path = f"Savefile/{save_stellar}/{save_planet}/{date}/fitting/{bin_size}/{bin_size}_t{exp_t}_{mode}_{filtername}_fit"
print("Fitting result save in:")
print(save_path)
# planet.transit_fitting(save_path,
# detrending_order=1,
# iterations=50000,
# burn_in = 25000,
# walkers=50,
# fit_rp_over_rs=True,
# fit_mid_time=True)
planet.transit_fitting(save_path,
detrending_order=1,
iterations=100000,
burn_in = 50000,
walkers=50,
fit_mid_time=True)
def lc_fitting(target_name, target_date,
mode_list = ["mod", "obs"],
run_nonbinned_fit = True,
run_binning_fit = True,
multiple_process = False,
avail_cpus = int(os.cpu_count()/2)):
"""
<<input>>
target_name : string ; target planet_name
planet_date : string ; target planet_date ; list in LC_syn_tk.ipynb
mode_list : list(string) ; consider "whole time"/"observable time" ; default = ['mod', 'obs']
run_nonbinned_fit : bool ; whether run non-binned_fit fitting or not ; default = True
run_binning_fit : bool ; whether run binning fitting or not ; default = True
multiple_process : bool ; whether simultaneously run differnt exp_t ; default = False
<<output>>
** : running ; execute the fitting code ; define in same file func_fitv2.py
"""
stellar_name = '-'.join(target_name.split('-')[:-1])
data = pickle.load(open(f"Savefile/{stellar_name}/{target_name}/{target_date}/time_flux/{target_name}_{target_date}.pickle",'rb'))
data_bin = pickle.load(open(f"Savefile/{stellar_name}/{target_name}/{target_date}/time_flux/{target_name}_bin_{target_date}.pickle",'rb'))
date = data["target_date"]
planet_tk = data["planet_object"]
exposure_list = data["exposure_list [sec]"]
filtername_list = data["filtername_list"] # 'Twinkle_ch0_filter','Twinkle_ch1_filter'
print(f"The filter list is: {filtername_list}")
binsize_list = data_bin["binsize_list [min]"]
# check the date from the saving path is the same as the synthetic object
if not target_date==date:
print("Something go wrong QQ")
return
for mode in mode_list:
index = 0
for filtername in filtername_list:
for exp_t in exposure_list[index]:
planet = copy.deepcopy(planet_tk)
if mode == "mod":
time_array = data["time_array"][filtername][f"exp_t{exp_t} [sec]"]
flux_array = data["mod_noise_array"][filtername][f"exp_t{exp_t} [sec]"]
flux_unc_array = np.full((len(data["mod_noise_array"][filtername][f"exp_t{exp_t} [sec]"]),),
data["err_per_exp [ppm]"][filtername][f"exp_t{exp_t} [sec]"]/1e6)
elif mode == "obs":
time_array = data["observable_array"][filtername][f"exp_t{exp_t} [sec]"]
flux_array = data["obs_noise_array"][filtername][f"exp_t{exp_t} [sec]"]
flux_unc_array = np.full((len(data["obs_noise_array"][filtername][f"exp_t{exp_t} [sec]"]),),
data["err_per_exp [ppm]"][filtername][f"exp_t{exp_t} [sec]"]/1e6)
add_observation(planet,
exp_t,
time_array,
flux_array,
flux_unc_array,
filtername)
print("Do fitting of non-binning data in date:")
print(f"{date} exp_t:{exp_t} datatype:{mode} filter:{filtername}")
if run_nonbinned_fit:
# For parallel computing
# We use the function of "multiprocessing.Process" to let our function "run_fitting" become one of the task.
# Then, we use .start() to let the CPU start to execute the task, and continue to do other tasks if we need.
# We can also use .join to let CPU wait for the previous tasks finish.
if multiple_process:
pool = multiprocessing.Pool(processes = avail_cpus)
pool.apply_async(run_fitting, args=(planet, date, exp_t, "non-binned", filtername, mode))
else:
run_fitting(planet, date, exp_t, "non-binned", filtername, mode)
index = index + 1
# for multiple_process, wait until the non-binned data finish
if run_nonbinned_fit and multiple_process:
pool.close()
pool.join()
for bin_size in binsize_list:
for mode in mode_list:
index = 0
for filtername in filtername_list:
for exp_t in exposure_list[index]:
planet_b = copy.deepcopy(planet_tk)
if data_bin[f"check_expvsbin_t{bin_size} [min]"][filtername][f"exp_t{exp_t} [sec]"]:
print(f"The bin_size{bin_size}(min) > exposure_time{exp_t}(sec), skip binning fitting")
continue
if mode == "mod":
time_array = data_bin[f"lc_b{bin_size}_mod [min]"][filtername][f"exp_t{exp_t} [sec]"].time.value
flux_array = data_bin[f"lc_b{bin_size}_mod [min]"][filtername][f"exp_t{exp_t} [sec]"].flux.value
flux_unc_array = data_bin[f"lc_b{bin_size}_mod [min]"][filtername][f"exp_t{exp_t} [sec]"].flux_err.value/1e6
elif mode == "obs":
time_array = data_bin[f"lc_b{bin_size}_obs [min]"][filtername][f"exp_t{exp_t} [sec]"].time.value
flux_array = data_bin[f"lc_b{bin_size}_obs [min]"][filtername][f"exp_t{exp_t} [sec]"].flux.value
flux_unc_array = data_bin[f"lc_b{bin_size}_obs [min]"][filtername][f"exp_t{exp_t} [sec]"].flux_err.value/1e6
time_array = time_array[np.isfinite(flux_array)]
flux_array = flux_array[np.isfinite(flux_array)]
flux_unc_array = flux_unc_array[np.isfinite(flux_unc_array)]
add_observation(planet_b,
exp_t,
time_array,
flux_array,
flux_unc_array,
filtername)
print(f"Do fitting of {bin_size}bin data in date:")
print(f"{date} exp_t:{exp_t} datatype:{mode} filter:{filtername}")
if run_binning_fit:
# For parallel computing
# We use the function of "multiprocessing.Process" to let our function "run_fitting" become one of the task.
# Then, we use .start() to let the CPU start to execute the task, and continue to do other tasks if we need.
# We can also use .join to let CPU wait for the previous tasks finish.
if multiple_process:
pool = multiprocessing.Pool(processes = avail_cpus)
pool.apply_async(run_fitting, args=(planet_b, date, exp_t, 'bin'+str(bin_size), filtername, mode))
else:
run_fitting(planet_b, date, exp_t, 'bin'+str(bin_size), filtername, mode)
index = index + 1
# for multiple_process, wait until the previos task become finish.
if run_binning_fit and multiple_process:
pool.close()
pool.join() | yu-twinkle | /yu_twinkle-0.0.2.tar.gz/yu_twinkle-0.0.2/yu_twinkle/func_fit.py | func_fit.py |
# pYthon Utilities
安装
```
$ pip install yu
```
## extractors - 数据提取
数据提取,支持:
* Field
* SkipField - 直接跳过
* PassField - 不做转换
* StringField - 字符串,支持长度验证
* IntegerField - 整数,支持最大、最小值验证
* FloatField - 浮点数
* DateField - 日期
* RowExtractor
* CSVExtractor
### 示例
csv.extract 的用法:
```python
import csv
from yu.extractors import csv as ce
fields = [
ce.StringField(min_length=2, max_length=4), # 姓名
ce.SkipField(), # 民族
ce.IntegerField(max_value=150), # 年龄
ce.FloatField(min_value=5, max_value=200), # 体重
ce.DateField(), # 生日
ce.PassField(), # 备注
]
with open('data/person.csv') as fp:
reader = csv.reader(fp)
for row in ce.extract(reader, fields=fields):
print(row)
```
### excel.extract 的用法
```python
import xlrd
from yu.extractors import excel as ee
fields = [
ee.StringField(min_length=2, max_length=4), # 姓名
ee.SkipField(), # 民族
ee.IntegerField(max_value=150), # 年龄
ee.FloatField(min_value=5, max_value=200), # 体重
ee.DateField(), # 生日
ee.PassField(), # 备注
]
book = xlrd.open_workbook('data/person.xlsx')
sheet = book.sheet_by_name('person')
for row in ee.extract(sheet, fields=fields):
print(row)
```
## utils - 其他工具
包括
* cached_property - 代码来自 Django 项目
* InstanceMeta - 类的自动实例化
* Instance - 类的自动实例化(继承方式)
### InstanceMeta 示例
```python
from yu.utils import InstanceMeta
class Color(metaclass=InstanceMeta, abstract=True):
def __str__(self):
return f'{self.name} = {self.value}'
class Red(Color):
name = 'red'
value = 'FF0000'
class Green(Color):
name = 'green'
value = '00FF00'
print(Red)
print(Green)
```
## formula
用法:
```python
# 定义公式
try:
面积公式 = Formula('面积 = 长 * 宽', '长方形面积')
except FormulaError as exc:
print(exc)
# 进行计算
context = {
'长': 16,
'宽': 15,
}
try:
面积公式(context)
except FormulaError as exc:
print(exc)
# 读取结果
print(context['面积'])
```
## 修改记录
v0.5.0
* 2017-12-28 添加 yu.formula
v0.4.1
* 2017-12-20 完善 yu.extractors, 封装返回值
v0.4.0
* 2017-12-15 增加 argparseutils 模块,支持 DateType, DatetimeType
v0.2.2
* 2017-12-15 完善 extractors.excel 和 extractors.csv
v0.2.1
* 2017-12-11 发布里增加 README.md, data/*
v0.2.0
* 2017-12-10 添加 yu.extractors.excel,处理 Excel 文件的数据提取
v0.1.1
* 2017-12-09 添加 yu.extractors.csv, 处理 CSV 文件的数据提取
| yu | /yu-0.5.0.tar.gz/yu-0.5.0/README.md | README.md |
import _thread
import inspect
import keyword
import linecache
import os
import pydoc
import sys
import tempfile
import time
import tokenize
import traceback
codeText = ""
__UNDEF__ = [] # a special sentinel object
def lookup(name, frame, locals):
"""Find the value for a given name in the given environment."""
if name in locals:
return 'local', locals[name]
if name in frame.f_globals:
return 'global', frame.f_globals[name]
if '__builtins__' in frame.f_globals:
builtins = frame.f_globals['__builtins__']
if type(builtins) is type({}):
if name in builtins:
return 'builtin', builtins[name]
else:
if hasattr(builtins, name):
return 'builtin', getattr(builtins, name)
return None, __UNDEF__
def scanvars(reader, frame, locals):
"""Scan one logical line of Python and look up values of variables used."""
vars, lasttoken, parent, prefix, value = [], None, None, '', __UNDEF__
for ttype, token, start, end, line in tokenize.generate_tokens(reader):
if ttype == tokenize.NEWLINE: break
if ttype == tokenize.NAME and token not in keyword.kwlist:
if lasttoken == '.':
if parent is not __UNDEF__:
value = getattr(parent, token, __UNDEF__)
vars.append((prefix + token, prefix, value))
else:
where, value = lookup(token, frame, locals)
vars.append((token, where, value))
elif token == '.':
prefix += lasttoken + '.'
parent = value
else:
parent, prefix = None, ''
lasttoken = token
return vars
def text(einfo, context=5):
global codeText
"""Return a plain text document describing a given traceback."""
etype, evalue, etb = einfo
if isinstance(etype, type):
etype = etype.__name__
pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
date = time.ctime(time.time())
head = "[=====Basic Part=====]\n%s\n%s\n%s" % (str(etype), pyver, date)
codeText = inspect.getinnerframes(etb, 10000)
frames = []
records = inspect.getinnerframes(etb, context)
for frame, file, lnum, func, lines, index in records:
file = file and os.path.abspath(file) or '?'
args, varargs, varkw, locals = inspect.getargvalues(frame)
call = ''
if func != '?':
call = 'in ' + func + \
inspect.formatargvalues(args, varargs, varkw, locals,
formatvalue=lambda value: '=' + pydoc.text.repr(value))
highlight = {}
def reader(lnum=[lnum]):
highlight[lnum[0]] = 1
try: return linecache.getline(file, lnum[0])
finally: lnum[0] += 1
vars = scanvars(reader, frame, locals)
rows = []
rows.append("[====================]\n\n\n[=====Data Part=====]")
done, dump = {}, []
for name, where, value in vars:
if name in done: continue
done[name] = 1
if value is not __UNDEF__:
if where == 'global': name = 'global ' + name
elif where != 'local': name = where + name.split('.')[-1]
dump.append('%s = %s' % (name, pydoc.text.repr(value)))
else:
dump.append(name + ' undefined')
rows.append('\n'.join(dump))
rows.append('[===================]\n\n\n[=====Raw Error=====]')
frames.append('\n%s\n' % '\n'.join(rows))
exception = ['%s: %s' % (str(etype), str(evalue))]
return head + ''.join(frames) + ''.join(exception) + '''
The above is a description of an error in a Python program. Here is
the original traceback:
%s
''' % ''.join(traceback.format_exception(etype, evalue, etb))+"\n[===================]"
class Hook:
"""A hook to replace sys.excepthook that shows tracebacks in HTML."""
def __init__(self, display=1, logdir=None, context=5, file=None,
format="html"):
self.display = display # send tracebacks to browser if true
self.logdir = logdir # log tracebacks to files if not None
self.context = context # number of source code lines per frame
self.file = file or sys.stdout # place to send the output
self.format = format
def __call__(self, etype, evalue, etb):
self.handle((etype, evalue, etb))
def handle(self, info=None):
global codeText
info = info or sys.exc_info()
formatter = text
plain = False
try:
doc = formatter(info, self.context)
except: # just in case something goes wrong
doc = ''.join(traceback.format_exception(*info))
plain = True
if self.display:
if plain:
doc = pydoc.html.escape(doc)
self.file.write('<pre>' + doc + '</pre>\n')
else:
self.file.write('<p>A problem occurred in a Python script.\n')
if self.logdir is not None:
suffix = ['.txt', '.html'][self.format=="html"]
(fd, path) = tempfile.mkstemp(suffix=suffix,prefix="pkmq-", dir=self.logdir)
try:
with os.fdopen(fd, 'w') as file:
file.write(doc)
msg = '%s contains the description of this error.' % path
except:
msg = 'Tried to save traceback to %s, but failed.' % path
if self.format == 'html':
self.file.write('<p>%s</p>\n' % msg)
codes = codeText[0].code_context
for l in range(len(codes)):
codes[l] = '%5d ' % (l+1) + codes[l].rstrip() + "\n"
res = "[Author: PuluterYu]\n\n\n[=====Raw Code Part=====]\n"+"".join(codes) + "[=======================]\n\n\n\n" + doc
with open("./yuLog.txt","w") as f:
f.write(res)
try:
self.file.write('发生异常,代码及报错已保存到./yuLog.txt\n请双击打开文件,并复制全部内容,粘贴到qq群内寻求帮助')
except: pass
handler = Hook().handle
def enable(display=1, logdir=None, context=5, format="html"):
"""Install an exception handler that formats tracebacks as HTML.
The optional argument 'display' can be set to 0 to suppress sending the
traceback to the browser, and 'logdir' can be set to a directory to cause
tracebacks to be written to files there."""
sys.excepthook = Hook(display=display, logdir=logdir,
context=context, format=format)
if not os.path.exists("./logs"): os.mkdir("logs")
enable(logdir="./logs/",format='text') | yuDebug | /yuDebug-1.0.2-py3-none-any.whl/yuDebug.py | yuDebug.py |
import cv2
import mediapipe as mp
import time
class FaceMeshDetector():
def __init__(self, staticMode=False, maxFaces=2, minDetectionCon=0.5, minTrackCon=0.5):
self.staticMode = staticMode
self.maxFaces = maxFaces
self.minDetectionCon = minDetectionCon
self.minTrackCon = minTrackCon
self.mpDraw = mp.solutions.drawing_utils
self.mpFaceMesh = mp.solutions.face_mesh
self.faceMesh = self.mpFaceMesh.FaceMesh(self.staticMode, self.maxFaces,
self.minDetectionCon, self.minTrackCon)
self.drawSpec = self.mpDraw.DrawingSpec(thickness=1, circle_radius=2)
def findFaceMesh(self, img, draw=True):
self.imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
self.results = self.faceMesh.process(self.imgRGB)
faces = []
if self.results.multi_face_landmarks:
for faceLms in self.results.multi_face_landmarks:
if draw:
self.mpDraw.draw_landmarks(img, faceLms, self.mpFaceMesh.FACEMESH_CONTOURS,
self.drawSpec, self.drawSpec)
face = []
for id,lm in enumerate(faceLms.landmark):
#print(lm)
ih, iw, ic = img.shape
x,y = int(lm.x*iw), int(lm.y*ih)
#cv2.putText(img, str(id), (x, y), cv2.FONT_HERSHEY_PLAIN,
# 0.7, (0, 255, 0), 1)
#print(id,x,y)
face.append([x,y])
faces.append(face)
return img, faces
def main():
cap = cv2.VideoCapture(0)
pTime = 0
detector = FaceMeshDetector(maxFaces=2)
while True:
success, img = cap.read()
img, faces = detector.findFaceMesh(img)
if len(faces)!= 0:
print(faces[0])
cTime = time.time()
fps = 1 / (cTime - pTime)
pTime = cTime
cv2.putText(img, f'FPS: {int(fps)}', (20, 70), cv2.FONT_HERSHEY_PLAIN,
3, (0, 255, 0), 3)
cv2.imshow("Image", img)
cv2.waitKey(1)
if __name__ == "__main__":
main() | yuan-cv | /yuan_cv-0.1.tar.gz/yuan_cv-0.1/yuan_cv/FaceMeshModule.py | FaceMeshModule.py |
import cv2
import mediapipe as mp
import time
class handDetector():
def __init__(self, mode=False, maxHands=2, detectionCon=0.5, trackCon=0.5):
self.mode = mode
self.maxHands = maxHands
self.detectionCon = detectionCon
self.trackCon = trackCon
self.mpHands = mp.solutions.hands
self.hands = self.mpHands.Hands(self.mode, self.maxHands,
self.detectionCon, self.trackCon)
self.mpDraw = mp.solutions.drawing_utils
def findHands(self, img, draw=True):
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
self.results = self.hands.process(imgRGB)
# print(results.multi_hand_landmarks)
if self.results.multi_hand_landmarks:
for handLms in self.results.multi_hand_landmarks:
if draw:
self.mpDraw.draw_landmarks(img, handLms,
self.mpHands.HAND_CONNECTIONS)
return img
def findPosition(self, img, handNo=0, draw=True):
lmList = []
if self.results.multi_hand_landmarks:
myHand = self.results.multi_hand_landmarks[handNo]
for id, lm in enumerate(myHand.landmark):
# print(id, lm)
h, w, c = img.shape
cx, cy = int(lm.x * w), int(lm.y * h)
# print(id, cx, cy)
lmList.append([id, cx, cy])
if draw:
cv2.circle(img, (cx, cy), 15, (255, 0, 255), cv2.FILLED)
return lmList
def main():
pTime = 0
cTime = 0
cap = cv2.VideoCapture(0)
detector = handDetector()
while True:
success, img = cap.read()
img = detector.findHands(img)
lmList = detector.findPosition(img)
if len(lmList) != 0:
print(lmList[4])
cTime = time.time()
fps = 1 / (cTime - pTime)
pTime = cTime
cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3,
(255, 0, 255), 3)
cv2.imshow("Image", img)
cv2.waitKey(1)
if __name__ == "__main__":
main() | yuan-cv | /yuan_cv-0.1.tar.gz/yuan_cv-0.1/yuan_cv/HandTrackingModule.py | HandTrackingModule.py |
# yuan-tool
御安python项目的公共库,包含:```数据库连接 ip处理 端口处理 网址处理 编码解码 路径处理 shell执行```等多个通用模块
## **切记不要随意改动已有方法并更新!!!可能会导致现有程序报错!!!**
## 安装
```pip install yuan-tool ```
## 功能清单
es/kafka/mongodb/mq/mysql/rabbitmq/redis/sqlite的连接工具类
网页的识别,请求处理
ip的识别,切分,合并处理
端口的切分,合并处理
协程工具类
加密/解密工具类
文件操作工具类
路径操作(拼接,绝对路径,相对路径)工具类
shell执行工具类
时间转换工具类
## 更新
由于已经编写好了```upload.py```脚本,更新流程如下:
1. 增加```setup.py```中的版本号
2. 更新引入包列表(如果有的话)
3. 根据情况调整一下```upload.py```的内容(python3/python之类的)
4. 执行```upload.py```
5. 查看是否更新成功/更新项目
``````shell
$ pip install -i https://pypi.python.org/pypi/ yuan-tool --upgrade
> 目前设置上传到pypi的只有yuantool目录下的内容,关于上传非包文件:
> 在setup.py同级目录下创建MANIFEST.in文件,里面的内容是需要上传的文件
>
> 例如,如果要包括项目下的所有文件:
> recursive-include fastproject *
>
> 为了将这些文件在安装时复制到site-packages中的包文件夹,需要将setup中的include_package_data设置为True
## 新建公共库
1. 获取项目下所有引入的包
```shell
$ pipreqs ./yuantool --force
```
2. 预备工作
```shell
$ python3 -m pip install setuptools wheel twine
```
3. 创建分发
```shell
$ python3 setup.py sdist bdist_wheel
```
4. 上传包
```shell
$ python3 -m twine upload dist/*
```
| yuan-tool | /yuan-tool-2.57.tar.gz/yuan-tool-2.57/README.md | README.md |
import string
import time
import re
import random
import copy
import inspect
import ctypes
from colorama.ansi import code_to_chars
from .enums import PLACE, POST_HINT
from .difinition import DEFAULT_GET_POST_DELIMITER, DEFAULT_COOKIE_DELIMITER
from .crypto import bytes_decode, str2bytes
def check_keys(require_keys, request_keys):
flag = True
lost_key = None
for key in require_keys:
if not (key in request_keys.keys() and request_keys[key]):
flag = False
lost_key = key
return flag, lost_key
def getattr_value(arr, key):
return getattr(arr, key) if key in arr else ''
def transform_bytes_str(s: str):
"""将str型的bytes内容解码"""
return bytes_decode(str2bytes(s))
def get_valid_filename(s):
"""
Return the given string converted to a string that can be used for a clean filename.
Stolen from Django I think
"""
s = str(s).strip().replace(' ', '_')
return re.sub(r'(?u)[^-\w.]', '', s)
def is_vars(keys, obj):
'''
判断对象中是否存在多个键值
keys和obj必须都为集合
return:
success: Boolean 是否全部包含
unhave: Dict 不存在keys的集合
'''
success = False
try:
result = keys.intersection(obj)
unhave = keys - result
dis = len(keys) - len(result)
# 判断是否keys全部存在
if dis == 0:
success = True
return success, unhave
except AttributeError as e:
print(e)
def format_name(name):
name = re.sub('[\s\-]+', '_', name)
return name.lower()
def qs_strr(s):
data = {}
if len(s) > 0:
for key in s:
data[key] = s[key][0]
return data
# 初始化数据
def init_data(keys, value=None):
v = {}
for key in keys:
v[key] = value
return v
# 将json转化为字符串,\n分割
def json_to_warp_str(json):
s = ''
for key in json:
s += f'{key}: {json[key]}\n'
return s
# 数据过滤
def data_filter(data):
data = re.sub(r'\s', '', data)
return data
def list_to_dict(l):
''' list 转 dict类型 '''
d = {i for i in l}
return d
def paramToDict(parameters, place=PLACE.GET, hint=POST_HINT.NORMAL) -> dict:
"""
Split the parameters into names and values, check if these parameters
are within the testable parameters and return in a dictionary.
"""
testableParameters = {}
if place == PLACE.COOKIE:
splitParams = parameters.split(DEFAULT_COOKIE_DELIMITER)
for element in splitParams:
parts = element.split("=")
if len(parts) >= 2:
testableParameters[parts[0]] = ''.join(parts[1:])
elif place == PLACE.GET:
splitParams = parameters.split(DEFAULT_GET_POST_DELIMITER)
for element in splitParams:
parts = element.split("=")
if len(parts) >= 2:
testableParameters[parts[0]] = ''.join(parts[1:])
elif place == PLACE.POST:
if hint == POST_HINT.NORMAL:
splitParams = parameters.split(DEFAULT_GET_POST_DELIMITER)
for element in splitParams:
parts = element.split("=")
if len(parts) >= 2:
testableParameters[parts[0]] = ''.join(parts[1:])
elif hint == POST_HINT.ARRAY_LIKE:
splitParams = parameters.split(DEFAULT_GET_POST_DELIMITER)
for element in splitParams:
parts = element.split("=")
if len(parts) >= 2:
key = parts[0]
value = ''.join(parts[1:])
if '[' in key:
if key not in testableParameters:
testableParameters[key] = []
testableParameters[key].append(value)
else:
testableParameters[key] = value
return testableParameters
def random_str(length=10, chars=string.ascii_lowercase):
return ''.join(random.sample(chars, length))
def get_except_dic(d: dict, *arg):
"""
将一个字典去除自定义的key值并返回字典
:param d: 初始字典
:param arg: 需要去除的key
:return: 去除指定key后的字典(原字典中没有指定的key也不会报错)
"""
c = set(d) - (set(d) - set(arg))
for key in c:
del d[key]
return d
def get_middle_text(text, prefix, suffix, index=0):
"""
获取中间文本的简单实现
:param text:要获取的全文本
:param prefix:要获取文本的前部分
:param suffix:要获取文本的后半部分
:param index:从哪个位置获取
:return:
"""
try:
index_1 = text.index(prefix, index)
index_2 = text.index(suffix, index_1 + len(prefix))
except ValueError:
# logger.log(CUSTOM_LOGGING.ERROR, "text not found pro:{} suffix:{}".format(prefix, suffix))
return ''
return text[index_1 + len(prefix):index_2]
def isListLike(value):
"""
Returns True if the given value is a list-like instance
>>> isListLike([1, 2, 3])
True
>>> isListLike('2')
False
"""
return isinstance(value, (list, tuple, set))
def findMultipartPostBoundary(post):
"""
Finds value for a boundary parameter in given multipart POST body
>>> findMultipartPostBoundary("-----------------------------9051914041544843365972754266\\nContent-Disposition: form-data; name=text\\n\\ndefault")
'9051914041544843365972754266'
"""
retVal = None
done = set()
candidates = []
for match in re.finditer(r"(?m)^--(.+?)(--)?$", post or ""):
_ = match.group(1).strip().strip('-')
if _ in done:
continue
else:
candidates.append((post.count(_), _))
done.add(_)
if candidates:
candidates.sort(key=lambda _: _[0], reverse=True)
retVal = candidates[0][1]
return retVal
def ltrim(text, left):
num = len(left)
if text[0:num] == left:
return text[num:]
return text
def random_colorama(text: str, length=4):
'''
在一段文本中随机加入colorama颜色
:return:
'''
records = []
start = -1
end = -1
index = 0
colors = range(31, 38)
w13scan = ()
colornum = 5
for char in text:
if char.strip() == "":
end = index
if start >= 0 and end - start >= length:
if text[start:end] == "w13scan":
w13scan = (start, end)
else:
records.append(
(start, end)
)
start = -1
end = -1
else:
if start == -1 and end == -1:
start = index
index += 1
if start > 0 and index - start >= length:
records.append((start, index))
length_records = len(records)
if length_records < colornum:
colornum = len(records)
elif 3 * colornum < colornum:
colornum = colornum + (length_records - 3 * colornum) // 2
slice = random.sample(records, colornum) # 从list中随机获取5个元素,作为一个片断返回
slice2 = []
for start, end in slice:
_len = end - start
rdint = random.randint(length, _len)
# 根据rdint长度重新组织start,end
rdint2 = _len - rdint
if rdint != 0:
rdint2 = random.randint(0, _len - rdint)
new_start = rdint2 + start
new_end = new_start + rdint
slice2.append((new_start, new_end))
slice2.append(w13scan)
slice2.sort(key=lambda a: a[0])
new_text = ""
indent_start = 0
indent_end = 0
for start, end in slice2:
indent_end = start
new_text += text[indent_start:indent_end]
color = random.choice(colors)
new_text += code_to_chars(color) + text[start:end] + code_to_chars(39)
indent_start = end
new_text += text[indent_start:]
return new_text
def updateJsonObjectFromStr(base_obj, update_str: str):
assert (type(base_obj) in (list, dict))
base_obj = copy.deepcopy(base_obj)
# 存储上一个value是str的对象,为的是更新当前值之前,将上一个值还原
last_obj = None
# 如果last_obj是dict,则为字符串,如果是list,则为int,为的是last_obj[last_key]执行合法
last_key = None
last_value = None
# 存储当前层的对象,只有list或者dict类型的对象,才会被添加进来
curr_list = [base_obj]
# 只要当前层还存在dict或list类型的对象,就会一直循环下去
while len(curr_list) > 0:
# 用于临时存储当前层的子层的list和dict对象,用来替换下一轮的当前层
tmp_list = []
for obj in curr_list:
# 对于字典的情况
if type(obj) is dict:
for k, v in obj.items():
# 如果不是list, dict, str类型,直接跳过
if type(v) not in (list, dict, str, int):
continue
# list, dict类型,直接存储,放到下一轮
if type(v) in (list, dict):
tmp_list.append(v)
# 字符串类型的处理
else:
# 如果上一个对象不是None的,先更新回上个对象的值
if last_obj is not None:
last_obj[last_key] = last_value
# 重新绑定上一个对象的信息
last_obj = obj
last_key, last_value = k, v
# 执行更新
obj[k] = update_str
# 生成器的形式,返回整个字典
yield base_obj
# 列表类型和字典差不多
elif type(obj) is list:
for i in range(len(obj)):
# 为了和字典的逻辑统一,也写成k,v的形式,下面就和字典的逻辑一样了,可以把下面的逻辑抽象成函数
k, v = i, obj[i]
if type(v) not in (list, dict, str, int):
continue
if type(v) in (list, dict):
tmp_list.append(v)
else:
if last_obj is not None:
last_obj[last_key] = last_value
last_obj = obj
last_key, last_value = k, v
obj[k] = update_str
yield base_obj
curr_list = tmp_list
def prepare_targets(targets):
"""
对于逗号分隔的targets(ip或域名)
从str型转为每个target以字典的key形式返回
:param targets:
:return:
"""
if isinstance(targets, dict):
return targets
else:
target_dict = {}
keys = targets.split(',')
for key in keys:
d = {'status': 0, 'data': {}}
target_dict.update({key: d})
return target_dict
def current_time():
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
def timestamp():
return time.time()
def contain(s1, s2):
''' 判断s2是否包含s1 '''
is_contain = False
row = re.findall(str(s1), s2)
if len(row) > 0:
is_contain = True
return is_contain, row
def randomStr(dig=6):
"""
生成随机字符串
:param dig: 几个字符
:return:
"""
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=dig))
def randomInt(start=0, end=10):
''' 生成随机整数 '''
return random.randint(start, end)
def clean(s):
# Remove invalid characters
s = re.sub('[^0-9a-zA-Z_]', '', s)
# Remove leading characters until we find a letter or underscore
s = re.sub('^[^a-zA-Z_]+', '', s)
if s.isnumeric(): s = '_' + s
return s
def compare_func2func(fun1, fun2, test_list=[], times=100, *arg, **kwarg):
import time
result = {}
a = time.time()
res1 = []
for i in range(times):
for example in test_list:
res1.append(fun1(example, *arg, **kwarg))
result['fun1_time'] = time.time() - a
result['fun1_res'] = res1
a = time.time()
res2 = []
for i in range(times):
for example in test_list:
res2.append(fun2(example, *arg, **kwarg))
result['fun2_time'] = time.time() - a
result['fun2_res'] = res2
return result
def substr(s: str, start: int, end: int):
return s[start: end]
def _parse_version(v: str):
v = v.strip()
# kill_start_alpha
while v and not v[0].isdigit():
v = v[1:]
# replace_spare
v = v.replace('-', '.').replace('_', '.').replace(' ', '.')
tv = v.split('.')
for index, sv in enumerate(tv):
if not sv.isdigit() and sv[0].isdigit() and sv[-1].isdigit():
a = re.findall('\d+', sv)
tv[index] = '.'.join(a)
return '.'.join(tv)
def compare_version(v1, v2, cp):
"""版本比较"""
# 1 判断是否包含数字,若有不存在数字
if not (bool(re.search(r'\d', v1)) and bool(re.search(r'\d', v2))):
if len(v1) == len(v2):
return eval('"{}"{}"{}"'.format(v1, cp, v2))
else:
raise ValueError('{} and {} can\'t compare!'.format(v1, v2))
# 2 处理版本号,规范点、横杠和'2sp3'这种情况
v1 = _parse_version(v1)
v2 = _parse_version(v2)
# 3 补齐所有的点
d1 = v1.count('.')
d2 = v2.count('.')
if d1 > d2:
v2 += '.0' * (d1 - d2)
else:
v1 += '.0' * (d2 - d1)
# 4 计算数字
total1 = total2 = step = 0
next_step = 1
d = v1.count('.')
l1 = v1.split('.')
l2 = v2.split('.')
for i in range(d, -1, -1):
tmp1 = int(''.join(filter(str.isdigit, l1[i])) or 0)
tmp2 = int(''.join(filter(str.isdigit, l2[i])) or 0)
lengh1 = len(str(tmp1))
lengh2 = len(str(tmp2))
total1 += next_step * tmp1
total2 += next_step * tmp2
step += max(lengh1, lengh2)
next_step = 10 ** step
return eval('{} {} {}'.format(total1, cp, total2))
def cpe_version_compare(target, cpe, *args):
dic = ['start_excluding', 'start_including', 'end_excluding', 'end_including']
# 特殊版本的额外匹配
if not ''.join(args):
# case: 【cpe:/a:openbsd:openssh:7.2p2】 with 【cpe:/a:openbsd:openssh:7.2:p2】
if target.replace(':', '') == cpe.replace(':', ''):
return True
else:
return False
# case: 【mac_os_xx】 with 【mac_os_x】
if not target.startswith(cpe + ':'):
return False
target_v = _parse_version(target[len(cpe) + 1:])
# 设置flag来判断是否匹配成功
flag = True
for i, rule in enumerate(args):
if not rule:
continue
rule_v = _parse_version(rule)
dl = rule_v.count('.')
dt = target_v.count('.')
if dt > dl:
rule_v += '.0' * (dt - dl)
else:
target_v += '.0' * (dl - dt)
total1 = total2 = step = 0
next_step = 1
d = target_v.count('.')
l1 = target_v.split('.')
l2 = rule_v.split('.')
for j in range(d, -1, -1): # d是数点,会比l1
tmp1 = int(''.join(filter(str.isdigit, l1[j])) or 0)
tmp2 = int(''.join(filter(str.isdigit, l2[j])) or 0)
lengh1 = len(str(tmp1))
lengh2 = len(str(tmp2))
total1 += next_step * tmp1
total2 += next_step * tmp2
step += max(lengh1, lengh2)
next_step = 10 ** step
# 等于号判断,若判断成功直接就匹配成功
if 'including' in dic[i] and total1 == total2:
break
elif 'start' in dic[i]:
if total2 < total1:
continue
else:
flag = False
break
else:
if total1 < total2:
continue
else:
flag = False
break
return flag
def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
try:
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
# pass
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
except Exception as err:
print(err)
def stop_thread(thread):
"""强制终止线程"""
_async_raise(thread.ident, SystemExit) | yuan-tool | /yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/common.py | common.py |
import paramiko
import os
import sys
import logging
import psutil
import functools
import subprocess
import tempfile
import asyncio
from concurrent.futures import ThreadPoolExecutor
from .crypto import md5
UNIX: bool = os.name == 'posix'
SYS: str = sys.platform
# os.name platform.system() sys.platform
# windows: nt Windows win32
# MacOS: posix Darwin darwin
# Linux: posix Linux linux
logger = logging.getLogger(__name__)
class ExecShellRemote:
"""
执行远程linux shell命令
"""
def __init__(self, hostname: str, port: int, username: str, password: str):
self.hostname = hostname
self.port = port
self.username = username
self.password = password
def create_remote_connection(self, info=False) -> bool:
try:
# 实例化SSHClient
self.client = paramiko.SSHClient()
# 自动添加策略,保存服务器的主机名和密钥信息
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.client.connect(hostname=self.hostname, port=self.port, username=self.username, password=self.password)
return True
except Exception as e:
logger.error(e, exc_info=info)
return False
def remote_exec(self, cmd):
stdin, stdout, stderr = self.client.exec_command(cmd)
return '\n'.join(stdout.readlines())
def ExecShell(cmdstring: str, shell=True):
"""
执行cmd命令
:return: (stdout,stderr)
:type: tuple
"""
if SYS == 'linux':
return ExecShellUnix(cmdstring, shell)
elif SYS == 'darwin':
return ExecShellMac(cmdstring, shell)
elif SYS == 'win32':
return ExecShellWindows(cmdstring, shell)
def ExecShellUnix(cmd: str, timeout=None, shell=True):
"""
Linux平台下执行shell命令
"""
a: str = ''
e: str = ''
try:
rx: str = md5(cmd)
# succ_f = tempfile.SpooledTemporaryFile(
# max_size=4096,
# mode='wb+',
# suffix='_succ',
# prefix='btex_' + rx,
# dir='/dev/shm'
# )
# err_f = tempfile.SpooledTemporaryFile(
# max_size=4096,
# mode='wb+',
# suffix='_err',
# prefix='btex_' + rx,
# dir='/dev/shm'
# )
# sub = subprocess.Popen(
# cmd,
# close_fds=True,
# shell=shell,
# bufsize=128,
# stdout=succ_f,
# stderr=err_f
# )
# sub.wait(timeout=timeout)
# err_f.seek(0)
# succ_f.seek(0)
# a = succ_f.read()
# e = err_f.read()
# if not err_f.closed: err_f.close()
# if not succ_f.closed: succ_f.close()
sub = subprocess.Popen(
cmd,
close_fds=True,
shell=shell,
bufsize=-1,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
a, e = sub.communicate()
if not sub.stdout.closed: sub.stdout.close()
if not sub.stderr.closed: sub.stderr.close()
try:
sub.kill()
except OSError:
pass
except Exception as err:
print(err)
try:
if isinstance(a, bytes): a = a.decode('utf-8')
if isinstance(e, bytes): e = e.decode('utf-8')
except Exception as err:
print(err)
return a, e
def ExecShellMac(cmd: str, shell=True):
'''
执行Shell命令(MacOS)
:param cmdstring : str
:param shell : (optional) The default is True.
:returns a,e
'''
a: str = ''
e: str = ''
try:
sub = subprocess.Popen(
cmd,
close_fds=True,
shell=shell,
bufsize=-1,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
a, e = sub.communicate()
if not sub.stdout.closed: sub.stdout.close()
if not sub.stderr.closed: sub.stderr.close()
try:
sub.kill()
except OSError:
pass
except Exception as err:
print(err)
try:
if isinstance(a, bytes): a = a.decode('utf-8')
if isinstance(e, bytes): e = e.decode('utf-8')
except Exception as err:
print(err)
return a, e
def ExecShellWindows(cmd: str, shell=True):
'''
执行Shell命令(MacOS)
:param cmdstring : str
:param shell : (optional) The default is True.
:returns a,e
'''
a: str = ''
e: str = ''
try:
sub = subprocess.Popen(
cmd,
close_fds=False,
shell=shell,
bufsize=-1,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
a, e = sub.communicate()
if not sub.stdout.closed: sub.stdout.close()
if not sub.stderr.closed: sub.stderr.close()
try:
sub.kill()
except OSError:
pass
except Exception as err:
print(err)
try:
if isinstance(a, bytes): a = a.decode('utf-8')
if isinstance(e, bytes): e = e.decode('utf-8')
except Exception as err:
print(err)
return a, e
async def AsyncExec(cmd, sudo=False, sudo_passwd=None):
"""
:param cmd: str or tuple or list
:param sudo:使用sudo(好像还有些问题)
:param sudo_passwd:
:return:
"""
proc = None
output = err = ''
if sudo:
cmd = ('sudo', '-S', '-p', 'xxxxx', *cmd)
try:
arg = {'stdin': asyncio.subprocess.PIPE,
'stdout': asyncio.subprocess.PIPE,
'stderr': asyncio.subprocess.PIPE}
if isinstance(cmd, str):
proc = await asyncio.create_subprocess_shell(cmd, **arg)
elif isinstance(cmd, (tuple, list)):
proc = await asyncio.create_subprocess_exec(*cmd, **arg)
output, err = await proc.communicate(None if not sudo else (sudo_passwd.encode() + b"\n"))
if err:
if sudo and err.strip().startswith(b'xxxxx'):
err = err[5:]
except:
raise
finally:
if proc:
try:
proc.terminate()
except ProcessLookupError:
pass
await proc.wait()
if err:
err = err.decode('utf8')
if output:
output = output.decode('utf8')
return output, err
def local_exec(cmd):
try:
result = os.popen(cmd)
return '\n'.join(result.readlines())
except Exception as e:
logger.error(e, exc_info=True)
return False
def local_exec_by_subprocess(cmd, **kwargs):
try:
p = subprocess.Popen(cmd, bufsize=-1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
close_fds=(SYS != "win32"), **kwargs)
(output, error) = p.communicate()
except Exception as e:
logger.error(e, exc_info=True)
return False
def perform(func, data, func_args=None, asynch=False, workers=None, progress=False, desc='Loading...'):
"""
Wrapper arround executable and the data list object.
Will execute the callable on each object of the list.
Parameters:
- `func`: callable stateless function. func is going to be called like `func(item, **func_args)` on all items in data.
- `data`: if stays None, will perform the action on all rows, else it will perfom the action on the data list.
- `func_args`: dict that will be passed by default to func in all calls.
- `asynch`: execute the task asynchronously
- `workers`: mandatory if asynch is true.
- `progress`: to show progress bar with ETA (if tqdm installed).
- `desc`: Message to print if progress=True
Returns a list of returned results
"""
if not callable(func):
raise ValueError('func must be callable')
# Setting the arguments on the function
func = functools.partial(func, **(func_args if func_args is not None else {}))
# The data returned by function
returned = list()
elements = data
try:
import tqdm
except ImportError:
progress = False
tqdm_args = dict()
# The message will appear on loading bar if progress is True
if progress is True:
tqdm_args = dict(desc=desc, total=len(elements))
# Runs the callable on list on executor or by iterating
if asynch:
if isinstance(workers, int):
if progress:
returned = list(tqdm.tqdm(ThreadPoolExecutor(max_workers=workers).map(func, elements), **tqdm_args))
else:
returned = list(ThreadPoolExecutor(max_workers=workers).map(func, elements))
else:
raise AttributeError('When asynch == True : You must specify a integer value for workers')
else:
if progress:
elements = tqdm.tqdm(elements, **tqdm_args)
for index_or_item in elements:
returned.append(func(index_or_item))
return returned
def schedule_job(func, blocking=False, **kwargs):
"""
:param func: 定时任务
:param kwargs:
trigger: 'interval' 时间间隔型任务 kwargs: seconds
'cron' 定时任务 kwargs: hour/minute
:return:
"""
if not blocking:
from apscheduler.schedulers.background import BackgroundScheduler
scheduler = BackgroundScheduler()
else:
from apscheduler.schedulers.blocking import BlockingScheduler
scheduler = BlockingScheduler()
scheduler.add_job(func, **kwargs)
scheduler.start()
def kill_child_process(pid):
parent = psutil.Process(pid)
for child in parent.children(recursive=True):
logger.info("kill child_process {}".format(child))
child.kill()
def exit_gracefully(signum, frame):
logger.info('Receive signal {} frame {}'.format(signum, frame))
pid = os.getpid()
kill_child_process(pid)
parent = psutil.Process(pid)
logger.info("kill self {}".format(parent))
parent.kill() | yuan-tool | /yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/execute.py | execute.py |
import os
import yaml
import shutil
import ruamel.yaml
import zipfile
import tarfile
import uuid
import logging
import pathlib
from io import BytesIO
logger = logging.getLogger(__name__)
def read_file(file, mode='r', encoding='utf-8'):
"""
:param file: 文件名
:param encoding: 编码,默认utf-8
:param mode: open方式,默认r
:return:
"""
with open(file, mode, encoding=encoding) as f:
return f.read()
def read_binary_file(file, mode='rb'):
"""
:param file: 文件名
:param mode: open方式,默认r
:return:
"""
with open(file, mode) as f:
return f.read()
def readline_file(file, encoding='utf-8'):
"""
:param file: 文件名
:param encoding: 编码,默认utf-8
:return:
"""
with open(file, 'r', encoding=encoding) as f:
return f.readlines()
def read_object(file, mode='r', encoding='utf-8'):
"""
返回文件对象
:param file:
:param mode:
:param encoding:
:return:
"""
f = open(file, mode, encoding=encoding)
return f
def read_yaml(config_path, config_name=''):
"""
config_path:配置文件路径
config_name:需要读取的配置内容,空则为全读
"""
if config_path and os.access(config_path, os.F_OK):
with open(config_path, 'r', encoding="utf-8") as f:
conf = yaml.safe_load(f.read()) # yaml.load(f.read())
if not config_name:
return conf
elif config_name in conf.keys():
return conf[config_name.upper()]
else:
raise KeyError('未找到对应的配置信息')
else:
raise ValueError('文件不存在,请输入正确的配置名称或配置文件路径')
def save_yaml(name, content, mode='w+'):
try:
with open(name, mode, encoding='utf-8') as f:
yaml.safe_dump(content, f, allow_unicode=True)
return True
except Exception as e:
raise IOError('yml文件写入错误-{}'.format(e))
def round_read_yaml(path):
"""
保留yaml所有注释,锚点的读取
"""
with open(path, 'r', encoding="utf-8") as f:
doc = ruamel.yaml.round_trip_load(f)
return doc
def round_save_yaml(path, doc):
"""
保留yaml所有注释,锚点的保存
"""
with open(path, 'w', encoding="utf-8") as f:
ruamel.yaml.round_trip_dump(doc, f, default_flow_style=False)
def read_file_index(file_path):
num = readline_file(file_path)
return int(num)
def save_file_index(file_path, cnt):
with open(file_path, 'w+', encoding="utf-8") as f:
f.write(str(cnt))
def move_file(src_file, dst_path) -> bool:
"""移动文件"""
if not os.path.isfile(src_file):
print("文件不存在")
return False
else:
if not os.path.exists(dst_path):
os.makedirs(dst_path)
shutil.move(src_file, dst_path)
print("move %s -> %s" % (src_file, dst_path))
return True
def rm_package(path):
"""删除文件夹以及其下所有文件"""
shutil.rmtree(path, ignore_errors=True)
logger.debug('删除文件夹{}'.format(path))
def rm_package_files(path):
"""删除文件夹下所有文件"""
ls = os.listdir(path)
for i in ls:
c_path = os.path.join(path, i)
if os.path.isdir(c_path):
rm_package_files(c_path)
else:
os.remove(c_path)
def deflated_zip(target, filename, file_url):
f = zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED)
f.write(filename, file_url)
f.close()
def extract_zip(zip_path, target_path):
"""
解压zip
解压成功:返回解压出的文件路径
解压失败:返回False
"""
try:
uuid_str = uuid.uuid4().hex
f = zipfile.ZipFile(zip_path, 'r')
f.extractall(path=target_path + '/' + uuid_str)
# corrector(target_path)
except Exception as e:
logger.error(e, exc_info=True)
return False
return target_path + '/' + uuid_str
def extract_tar(src_file=None, dst_path='./', file_obj=None, _mode='r:gz'):
"""
默认解压gzip压缩包
:param _mode: r:gz r:bz2 r:xz
:param src_file: 源文件
:param dst_path: 解压路径
:param file_obj: 文件对象
:return:
"""
if not src_file and not file_obj:
raise ValueError('Source file and byte data must fill in a')
if src_file:
_content = read_binary_file(src_file)
elif file_obj:
_content = file_obj
else:
raise BaseException('Unknown error getting file object')
_obj = tarfile.open(fileobj=BytesIO(_content), mode=_mode)
_filenames = _obj.getnames()
for _file in _filenames:
_obj.extract(_file, dst_path)
def extract_tar_obj(src_file=None, dst_path='./', file_obj=None, _mode='r:gz'):
"""
默认解压gzip压缩包
:param _mode: r:gz r:bz2 r:xz
:param src_file: 源文件
:param dst_path: 解压路径
:param file_obj: 文件对象
:return:
"""
if not src_file and not file_obj:
raise ValueError('Source file and byte data must fill in a')
if src_file:
_content = read_binary_file(src_file)
elif file_obj:
_content = file_obj
else:
raise BaseException('Unknown error getting file object')
_obj = tarfile.open(fileobj=BytesIO(_content), mode=_mode)
_filenames = _obj.getnames()
return _obj, _filenames
def get_filename(file, only_file=True):
""" 获取文件名 """
if only_file:
file = pathlib.Path(file).name
return file[:file.find('.')] | yuan-tool | /yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/file.py | file.py |
import sys
import time
import asyncio
import logging
from threading import Thread
logger = logging.getLogger(__name__)
# TODO 需要增加异常输出
class Coro(Thread):
def __init__(self, name='coroThread', sem=40, daemon=False):
"""
开一条线程单独去处理所有的协程任务
:param name: 线程名
:param sem: 协程并发量控制
:param daemon:
"""
super().__init__(name=name, daemon=daemon)
self.loop = asyncio.new_event_loop()
self.tasks = {}
# self.loop.set_exception_handler(self.custom_exception_handler)
self._sem_count = sem
self.sem = None
def __getitem__(self, item):
try:
return self.tasks[item]
except KeyError:
print('任务{}未存在'.format(item))
raise
def __repr__(self):
d = {}
for name in self.tasks:
d[name] = {'state': self[name]._state}
return str(d)
def run(self) -> None:
try:
asyncio.set_event_loop(self.loop)
except:
logger.error('协程启动失败')
sys.exit()
try:
self.loop.run_forever()
finally:
self.loop.run_until_complete(self.loop.shutdown_asyncgens())
self.loop.close()
async def sem_task(self, coro):
# 对task增加信号量,限制同一时间正在执行的任务数
if not self.sem:
self.sem = asyncio.Semaphore(self._sem_count)
async with self.sem:
return await coro
def add_task(self, coro, name=None, sem=False):
if name in self.tasks:
return False
if sem:
task = self.loop.create_task(self.sem_task(coro))
else:
task = self.loop.create_task(coro, name=name)
self.loop._csock.send(b'\0')
name = task.get_name()
self.tasks[name] = task
return name
def status(self, name):
return self[name]._state
def stop_task(self, name, nowait=False):
self[name].cancel()
if not nowait:
while not self.tasks[name].cancelled():
time.sleep(0.5)
def get_result(self, name):
try:
res = self[name].result()
del self.tasks[name]
except asyncio.exceptions.CancelledError:
print('Task {} 已取消'.format(name))
res = '任务已取消'
except Exception as e:
res = str(e)
return res
def is_done(self, name):
return self[name].done() | yuan-tool | /yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/coro.py | coro.py |
import base64
import hashlib
import logging
import binascii
from Crypto.Cipher import AES
from pyDes import des, PAD_PKCS5, ECB, CBC
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import algorithms
logger = logging.getLogger(__name__)
def xor(bin1, bin2) -> str:
"""基本XOR方法,用来在特定情况下代替python的^符号"""
return '0' if bin1 == bin2 else '1'
def md5(s, salt='', encoding='utf-8') -> str:
if isinstance(s, str):
return hashlib.md5((s + salt).encode(encoding=encoding)).hexdigest()
else:
return hashlib.md5(s).hexdigest()
def base64Encode(s) -> bytes:
b = str(s).encode('utf-8')
return bytes2base64(b)
def base64Decode(s) -> str:
s = str(s)
return base64.b64decode(s).decode('utf-8')
def bytes2base64(b: bytes):
return base64.b64encode(b)
def bytes_decode(b: bytes, default='utf-8') -> str:
"""bytes自动解码,可以使用默认值,默认值失败就会使用cchardet尝试解码"""
import cchardet
try:
res = b.decode(default)
except:
detect = cchardet.detect(b)
code = detect['encoding']
res = b.decode(code)
return res
def asc2int(sx) -> (str, tuple):
"""获取字符、字符串的ascii码值"""
if not isinstance(sx, str):
sx = str(sx)
return ord(sx) if len(sx) == 1 else tuple(ord(x) for x in sx)
def asc2hex(asc_str) -> str:
"""把字符串转换为16进制字符"""
asc_hex_arr = [[int2hex(asc2int(i))] for i in asc_str]
result = ''
for hex_c in asc_hex_arr:
hex_c = capitalize_hex(hex_c[0])
result = result + hex_c
return result
def int2hex(x: int) -> str:
"""10进制转16进制"""
return hex(x)
def int2asc(x: int) -> str:
"""ascii码值转对应字符"""
return chr(x)
def str2bytes(s: str) -> bytes:
return s.encode('raw_unicode_escape')
def bytes_to_hex(bs: bytes) -> str:
"""bytes转16进制字符串"""
# return ''.join(['%02X ' % b for b in bs]) #这样也可以
result = ''
for b_int_str in bs:
b_hex_str = '%02X ' % b_int_str # 另一种方式,把10进制字符串转换成16进制字符串
result = result + capitalize_hex(b_hex_str)
return result
def capitalize_bin(bin_str: str):
"""格式二进制字符串:去除ob和空格,并且如果不足8位,在前面添加0补齐"""
bin_str = bin_str.replace('0b', '').replace(' ', '')
if len(bin_str) % 8 == 0:
pass
else:
prex = 8 - len(bin_str)
bin_str = '0' * prex + bin_str
return bin_str
def str2bin(s: str) -> str:
"""字符串转2进制字符串"""
result = ''
for i in s:
result = result + capitalize_bin(bin(ord(i))) # capitalizeBin_str(bin(ord(i)):把单个字符转换成二进制
return result
def bin2str(b: str) -> str:
"""2进制转字符串"""
b = b.replace('0b', '').replace(' ', '')
if len(b) % 8 == 0:
b_array = [b[i:i + 8] for i in range(0, len(b), 8)]
# print(b_array)
result = ''
for i in b_array:
result = result + chr(int(i, 2)) # chr(int(i, 2)):把二进制转化成单个字符
return result
else:
raise ValueError
def bin2hex(bin_str) -> str:
"""2进制字符串转换成16进制字符串"""
bin_str = capitalize_bin(bin_str)
return capitalize_hex(int2hex(int(bin_str, 2)).replace('0x', ''))
def bin_xor_bin(bin_str1, bin_str2) -> str:
"""2进制字符串进行XOR计算"""
bin_str1 = capitalize_bin(bin_str1)
bin_str2 = capitalize_bin(bin_str2)
if len(bin_str1) == len(bin_str2):
result = ''
for i in range(0, len(bin_str1)):
result = result + xor(bin_str1[i], bin_str2[i])
return result
else:
raise ValueError
def capitalize_hex(hex_str: str):
"""格式16进制字符串:去除0x和空格,并且如果字符串只有1位,在前面补0"""
hex_str = hex_str.replace('0x', '').replace('0X', '').replace(' ', '')
if len(hex_str) % 2 == 0:
return hex_str
elif len(hex_str) == 1:
return '0' + hex_str
else:
raise ValueError
def hex_to_bytes(s: str) -> bytes:
"""16进制转bytes"""
return binascii.a2b_hex(s)
def hex2int(x: str) -> int:
"""16进制转10进制"""
return int(x, 16)
def hex2bin(hex_str: str) -> str:
"""16进制转2进制字符串"""
hex_str = capitalize_hex(hex_str)
return capitalize_bin(bin(hex2int(hex_str)))
def hex2asc(hex_str: str) -> str:
hex_str = capitalize_hex(hex_str)
hex_str_arr = hex2hex_arr(hex_str)
result = ''
for hex_c in hex_str_arr:
hex_int = int(hex_c, 16)
result = result + int2asc(hex_int)
return result
def hex2hex_arr(hex_str: str) -> list:
"""把16进制字符串转换成2个2个一对的16进制数组"""
hex_str = capitalize_hex(hex_str)
hex_str_arr = [hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]
return hex_str_arr
def hex_xor_hex_str(hex_str1, hex_str2) -> str:
"""把16进制字符串进行XOR计算"""
hex_str1 = capitalize_hex(hex_str1)
hex_str2 = capitalize_hex(hex_str2)
if len(hex_str1) == len(hex_str2):
hex_arr1 = hex2hex_arr(hex_str1) # 把16进制两两分组
hex_arr2 = hex2hex_arr(hex_str2)
result = ''
for i in range(0, len(hex_arr1)):
bin_str1 = hex2bin(hex_arr1[i]) # 16进制转换成2进制
bin_str2 = hex2bin(hex_arr2[i])
result_bin_str = bin_xor_bin(bin_str1, bin_str2) # 2进制xor计算
result_hex_str = bin2hex(result_bin_str) # 2进制转换成16进制
result = result + result_hex_str
return result
else:
raise ValueError
def change_byte(byte_str, offset, new_byte):
"""改变bytes中指定位置的byte"""
if offset > len(byte_str):
exit()
result = b''
i_num = 0
for i in byte_str:
i = hex_to_bytes(hex(i))
if i_num == offset:
byte_s = new_byte
else:
byte_s = i
result = result + byte_s
i_num = i_num + 1
return result
class CryptoModel:
"""
AES加密类
"""
def __init__(self, key: str, iv: str, mode=AES.MODE_CBC):
self.key = key.encode()
self.iv = iv.encode()
self.mode = mode
@staticmethod
def padding(text: bytes):
padding_0a = (16 - len(text) % 16) * b' '
return text + padding_0a
@staticmethod
def pkcs7_padding(data):
if not isinstance(data, bytes):
data = data.encode()
padder = padding.PKCS7(algorithms.AES.block_size).padder()
padded_data = padder.update(data) + padder.finalize()
return padded_data
@staticmethod
def pkcs7_unpadding(padded_data):
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
data = unpadder.update(padded_data)
try:
uppadded_data = data + unpadder.finalize()
except ValueError:
raise Exception('无效的加密信息!')
else:
return uppadded_data
def aes_encode(self, text: bytes):
obj = AES.new(self.key, self.mode, self.iv)
data = self.pkcs7_padding(text)
return obj.encrypt(data)
def aes_decode(self, data: bytes):
obj = AES.new(self.key, self.mode, self.iv)
return obj.decrypt(data).rstrip(b"\x01"). \
rstrip(b"\x02").rstrip(b"\x03").rstrip(b"\x04").rstrip(b"\x05"). \
rstrip(b"\x06").rstrip(b"\x07").rstrip(b"\x08").rstrip(b"\x09"). \
rstrip(b"\x0a").rstrip(b"\x0b").rstrip(b"\x0c").rstrip(b"\x0d"). \
rstrip(b"\x0e").rstrip(b"\x0f").rstrip(b"\x10")
def encrypt(self, data):
' 加密函数 '
cryptor = AES.new(self.key, self.mode, self.iv)
return binascii.b2a_hex(cryptor.encrypt(data)).decode()
def decrypt(self, data):
' 解密函数 '
cryptor = AES.new(self.key, self.mode, self.iv)
return cryptor.decrypt(binascii.a2b_hex(data)).decode()
class DESModel:
"""
DES加密类
"""
def __init__(self, key, iv=None, mode=ECB):
"""
:param key: Key
:param iv: Initialization vector
:param mode: algorithm
"""
if mode == ECB and iv is not None:
raise ValueError('MODE ECB can not IV')
self.des = des(key=key, mode=mode, IV=iv, padmode=PAD_PKCS5)
def encrypt(self, data, **kwargs):
res = self.des.encrypt(data, **kwargs)
return binascii.b2a_hex(res)
def decrypt(self, data, **kwargs):
return self.des.decrypt(binascii.a2b_hex(data), **kwargs) | yuan-tool | /yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/crypto.py | crypto.py |
acceptedExt = [
'.php', '.php3', '.php4', '.php5', '.php7', '.phtml',
'.asp', '.aspx', '.ascx', '.asmx',
'.chm', '.cfc', '.cfmx', '.cfml',
'.py',
'.rb',
'.pl',
'.cgi',
'.jsp', '.jhtml', '.jhtm', '.jws',
'.htm', '.html',
'.do', '.action', ''
]
ignoreParams = [
'submit',
'_',
'_t',
'rand',
'hash'
]
logoutParams = [
'logout',
'log_out',
'loginesc',
'loginout',
'delete',
'signout',
'logoff',
'signoff',
'exit',
'quit',
'byebye',
'bye-bye',
'clearuser',
'invalidate',
'reboot',
'shutdown',
]
GITHUB_REPORT_OAUTH_TOKEN = "NTYzYjhmZWJjYzc0Njg2ODJhNzhmNDg1YzM0YzlkYjk3N2JiMzE3Nw=="
# sqlmap report
# Default delimiter in cookie values
DEFAULT_COOKIE_DELIMITER = ';'
# Default delimiter in GET/POST values
DEFAULT_GET_POST_DELIMITER = '&'
# Regular expression for XML POST data
XML_RECOGNITION_REGEX = r"(?s)\A\s*<[^>]+>(.+>)?\s*\Z"
# Regular expression used for detecting JSON POST data
JSON_RECOGNITION_REGEX = r'(?s)\A(\s*\[)*\s*\{.*"[^"]+"\s*:\s*("[^"]*"|\d+|true|false|null).*\}\s*(\]\s*)*\Z'
# Regular expression used for detecting JSON-like POST data
JSON_LIKE_RECOGNITION_REGEX = r"(?s)\A(\s*\[)*\s*\{.*'[^']+'\s*:\s*('[^']+'|\d+).*\}\s*(\]\s*)*\Z"
# Regular expression used for detecting multipart POST data
MULTIPART_RECOGNITION_REGEX = r"(?i)Content-Disposition:[^;]+;\s*name="
# Regular expression used for detecting Array-like POST data
ARRAY_LIKE_RECOGNITION_REGEX = r"(\A|%s)(\w+)\[\]=.+%s\2\[\]=" % (
DEFAULT_GET_POST_DELIMITER, DEFAULT_GET_POST_DELIMITER)
notAcceptedExt = [
"css",
"jpg",
"jpeg",
"png",
"gif",
"wmv",
"a3c",
"ace",
"aif",
"aifc",
"aiff",
"arj",
"asf",
"asx",
"attach",
"au",
"avi",
"bin",
"bmp",
"cab",
"cache",
"class",
"djv",
"djvu",
"dwg",
"es",
"esl",
"exe",
"fif",
"fvi",
"gz",
"hqx",
"ice",
"ico",
"ief",
"ifs",
"iso",
"jar",
"jpe",
"kar",
"mdb",
"mid",
"midi",
"mov",
"movie",
"mp",
"mp2",
"mp3",
"mp4",
"mpeg",
"mpeg2",
"mpg",
"mpg2",
"mpga",
"msi",
"pac",
"pdf",
"ppt",
"psd",
"qt",
"ra",
"ram",
"rar",
"rm",
"rpm",
"snd",
"svf",
"tar",
"tgz",
"tif",
"tiff",
"tpl",
"ttf",
"uff",
"wav",
"wma",
"zip",
"woff2"
]
XSS_EVAL_ATTITUDES = ['onbeforeonload', 'onsubmit', 'ondragdrop', 'oncommand', 'onbeforeeditfocus', 'onkeypress',
'onoverflow', 'ontimeupdate', 'onreset', 'ondragstart', 'onpagehide', 'onunhandledrejection',
'oncopy',
'onwaiting', 'onselectstart', 'onplay', 'onpageshow', 'ontoggle', 'oncontextmenu', 'oncanplay',
'onbeforepaste', 'ongesturestart', 'onafterupdate', 'onsearch', 'onseeking',
'onanimationiteration',
'onbroadcast', 'oncellchange', 'onoffline', 'ondraggesture', 'onbeforeprint', 'onactivate',
'onbeforedeactivate', 'onhelp', 'ondrop', 'onrowenter', 'onpointercancel', 'onabort',
'onmouseup',
'onbeforeupdate', 'onchange', 'ondatasetcomplete', 'onanimationend', 'onpointerdown',
'onlostpointercapture', 'onanimationcancel', 'onreadystatechange', 'ontouchleave',
'onloadstart',
'ondrag', 'ontransitioncancel', 'ondragleave', 'onbeforecut', 'onpopuphiding', 'onprogress',
'ongotpointercapture', 'onfocusout', 'ontouchend', 'onresize', 'ononline', 'onclick',
'ondataavailable', 'onformchange', 'onredo', 'ondragend', 'onfocusin', 'onundo', 'onrowexit',
'onstalled', 'oninput', 'onmousewheel', 'onforminput', 'onselect', 'onpointerleave', 'onstop',
'ontouchenter', 'onsuspend', 'onoverflowchanged', 'onunload', 'onmouseleave',
'onanimationstart',
'onstorage', 'onpopstate', 'onmouseout', 'ontransitionrun', 'onauxclick', 'onpointerenter',
'onkeydown', 'onseeked', 'onemptied', 'onpointerup', 'onpaste', 'ongestureend', 'oninvalid',
'ondragenter', 'onfinish', 'oncut', 'onhashchange', 'ontouchcancel', 'onbeforeactivate',
'onafterprint', 'oncanplaythrough', 'onhaschange', 'onscroll', 'onended', 'onloadedmetadata',
'ontouchmove', 'onmouseover', 'onbeforeunload', 'onloadend', 'ondragover', 'onkeyup',
'onmessage',
'onpopuphidden', 'onbeforecopy', 'onclose', 'onvolumechange', 'onpropertychange', 'ondblclick',
'onmousedown', 'onrowinserted', 'onpopupshowing', 'oncommandupdate', 'onerrorupdate',
'onpopupshown',
'ondurationchange', 'onbounce', 'onerror', 'onend', 'onblur', 'onfilterchange', 'onload',
'onstart',
'onunderflow', 'ondragexit', 'ontransitionend', 'ondeactivate', 'ontouchstart', 'onpointerout',
'onpointermove', 'onwheel', 'onpointerover', 'onloadeddata', 'onpause', 'onrepeat',
'onmouseenter',
'ondatasetchanged', 'onbegin', 'onmousemove', 'onratechange', 'ongesturechange',
'onlosecapture',
'onplaying', 'onfocus', 'onrowsdelete']
TOP_RISK_GET_PARAMS = {"id", 'action', 'type', 'm', 'callback', 'cb'} | yuan-tool | /yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/difinition.py | difinition.py |
import re
import json
import requests
import urllib.parse
import base64
import sys
import hashlib
from .difinition import GITHUB_REPORT_OAUTH_TOKEN
def dataToStdout(data, bold=False):
"""
Writes text to the stdout (console) stream
"""
sys.stdout.write(data)
try:
sys.stdout.flush()
except IOError:
pass
return
def createGithubIssue(errMsg, excMsg):
_ = re.sub(r"'[^']+'", "''", excMsg)
_ = re.sub(r"\s+line \d+", "", _)
_ = re.sub(r'File ".+?/(\w+\.py)', r"\g<1>", _)
_ = re.sub(r".+\Z", "", _)
_ = re.sub(r"(Unicode[^:]*Error:).+", r"\g<1>", _)
_ = re.sub(r"= _", "= ", _)
errMsg = re.sub("cookie: .*", 'cookie: *', errMsg, flags=re.I | re.S)
key = hashlib.md5(_.encode()).hexdigest()[:8]
msg = "\ndo you want to automatically create a new (anonymized) issue "
msg += "with the unhandled exception information at "
msg += "the official Github repository? [y/N] "
try:
choice = input(msg)
except:
choice = 'n'
if choice.lower() != 'y':
return False
try:
req = requests.get("https://api.github.com/search/issues?q={}".format(
urllib.parse.quote("repo:w-digital-scanner/w13scan Unhandled exception (#{})".format(key))))
except Exception as e:
return False
_ = json.loads(req.text)
try:
duplicate = _["total_count"] > 0
closed = duplicate and _["items"][0]["state"] == "closed"
if duplicate:
warnMsg = "issue seems to be already reported"
if closed:
warnMsg += " and resolved. Please update to the latest "
dataToStdout('\r' + "[x] {}".format(warnMsg) + '\n\r')
return False
except KeyError:
return False
data = {
"title": "Unhandled exception (#{})".format(key),
"body": "```\n%s\n```\n```\n%s\n```" % (errMsg, excMsg),
"labels": ["bug"]
}
headers = {
"Authorization": "token {}".format(base64.b64decode(GITHUB_REPORT_OAUTH_TOKEN.encode()).decode())
}
try:
r = requests.post("https://api.github.com/repos/w-digital-scanner/w13scan/issues", data=json.dumps(data),
headers=headers)
except Exception as e:
return False
issueUrl = re.search(r"https://github\.com/w-digital-scanner/w13scan/issues/\d+", r.text)
if issueUrl:
infoMsg = "created Github issue can been found at the address '%s'" % issueUrl.group(0)
dataToStdout('\r' + "[*] {}".format(infoMsg) + '\n\r')
return True
return False | yuan-tool | /yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/upload.py | upload.py |
# We define some constants
class DBMS:
DB2 = 'IBM DB2 database'
MSSQL = 'Microsoft SQL database'
ORACLE = 'Oracle database'
SYBASE = 'Sybase database'
POSTGRE = 'PostgreSQL database'
MYSQL = 'MySQL database'
JAVA = 'Java connector'
ACCESS = 'Microsoft Access database'
INFORMIX = 'Informix database'
INTERBASE = 'Interbase database'
DMLDATABASE = 'DML Language database'
SQLITE = 'SQLite database'
UNKNOWN = 'Unknown database'
class OS:
LINUX = "Linux"
WINDOWS = "Windows"
DARWIN = "Darwin"
class PLACE:
GET = "GET"
POST = "POST"
URI = "URI"
COOKIE = "Cookie"
USER_AGENT = "User-Agent"
REFERER = "Referer"
HOST = "Host"
class HTTPMETHOD:
GET = "GET"
POST = "POST"
HEAD = "HEAD"
PUT = "PUT"
DELETE = "DELETE"
TRACE = "TRACE"
OPTIONS = "OPTIONS"
CONNECT = "CONNECT"
PATCH = "PATCH"
class POST_HINT:
NORMAL = "NORMAL"
SOAP = "SOAP"
JSON = "JSON"
JSON_LIKE = "JSON-like"
MULTIPART = "MULTIPART"
XML = "XML (generic)"
ARRAY_LIKE = "Array-like"
class WEB_PLATFORM:
PHP = "Php"
ASP = "Asp"
ASPX = "Aspx"
JAVA = "Java"
PYTHON = 'Python'
class LEVEL:
NONE = 0
LOW = 1
MIDDLE = 2
HIGHT = 3
POST_HINT_CONTENT_TYPES = {
POST_HINT.JSON: "application/json",
POST_HINT.JSON_LIKE: "application/json",
POST_HINT.MULTIPART: "multipart/form-data",
POST_HINT.SOAP: "application/soap+xml",
POST_HINT.XML: "application/xml",
POST_HINT.ARRAY_LIKE: "application/x-www-form-urlencoded; charset=utf-8",
}
class VulType:
CMD_INNJECTION = "cmd_injection"
CODE_INJECTION = "code_injection"
XSS = "xss"
SQLI = "sqli"
DIRSCAN = "dirscan"
PATH_TRAVERSAL = "path_traversal"
XXE = "xxe"
BRUTE_FORCE = "brute_force"
JSONP = "jsonp"
SSRF = "ssrf"
BASELINE = "baseline"
REDIRECT = "redirect"
CRLF = "crlf"
SENSITIVE = "sensitive"
SMUGGLING = 'smuggling' | yuan-tool | /yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/enums.py | enums.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.